• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 235
  • Last Modified:

populating combo box from databse in jsp

I want to know how to populate key value pairs in combobox from a database in jsp. Actually i am new to java programming so please let me know the code for it.Thanx in advance.
0
harpreetmarwaha
Asked:
harpreetmarwaha
1 Solution
 
rajbhaskarCommented:
Try something like this:

<%@page import="java.sql.*" %>
<%
// load the database driver
Class.forName("driver.class").newInstance();

// get a connection to the database
Connection con= DriverManager.getConnection("con.string", "username", "password");
Statement stmt= con.createStatement();

// run the query
String query= "SELECT key, value, FROM YourTable";
ResultSet rs= stmt.executeQuery(query);
%>

<!-- create the combo box -->
<select name="mySelectBox">
<% while (rs.next()) { %>
<option value="<%=rs.getString("key")%>"><%=rs.getString("value")%></option>
<% } // end loop %>
</select>

<%
// close connection to database
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (con != null) con.close();
%>

A slightly more elegant way to do it would be to do all teh database stuff in a bean and return a Map which you could use to populate the combo box using something like my own HtmlForms package (http://lordofthemoon.com/computing/downloads.php?file=/computing/downloads/htmlforms.html )

HTH,
Raj.
0
 
CleanupPingCommented:
harpreetmarwaha:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
EXPERTS:
Post your closing recommendations!  No comment means you don't care.
0
 
tomboshellCommented:
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:
Accept Rajbhaskar's comment
Please leave any comments here within the next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

Thomas Boshell
EE Cleanup Volunteer
0

Featured Post

Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now