How to retrieve the value from database into dropdown list using JDBC & SQL 2005?
JSP Code:
Create table country(country_id,country) in database and try the following code:
<%@page import="java.sql.*"%> <html> <form name="form" method="post" > <b>Select a country:</b> </td> <select name="sel"><option value=""><---Select---></option> <% Class.forName("com.mysql.jdbc.Driver").newInstance(); String connectionURL = "jdbc:mysql://localhost:3306/test";; Connection connection= DriverManager.getConnection(connectionURL, "root", "root"); PreparedStatement psmnt = connection.prepareStatement("select * from country "); ResultSet results = psmnt.executeQuery(); while(results.next()){ String name = results.getString(2); String id = results.getString(1); %><option value="<%= name %>"> <% out.println(name); %> </option> <%} results.close(); psmnt.close(); %> </select><br> <input type="submit" value="Submit"/><br> </form> <%String option=request.getParameter("sel"); if(option==null){ } else{%> <input type="text" value="<%=option%>"> <% } %> </html>
Java Code:
import java.sql.*; import java.awt.*; import javax.swing.*; import java.awt.event.*; class ComboExample { ComboExample() { JFrame f = new JFrame(); f.getContentPane().setLayout(null); final JComboBox combo = new JComboBox(); try { Class.forName("com.mysql.jdbc.Driver"); Connection connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root","root"); Statement st = connect.createStatement(); ResultSet rs = st.executeQuery("Select name from data"); while (rs.next()) { combo.addItem(rs.getString("name")); } } catch (Exception ex) { } combo.setBounds(20, 50, 150, 20); f.add(combo); f.setSize(400, 200); f.setVisible(true); } public static void main(String[] args) { ComboExample c = new ComboExample(); } }
Ads