how to fetch the dropdown values from database and display in jsp:
Dynamically Fetch data from Mysql to (drop down) select option in Jsp. This post illustrates, to fetch the data from the mysql database and display in select option element in Jsp. You should know the following post before going through this post i.e :
How to Connect Mysql database to jsp.
How to create database in MySql and insert data into database.
Following database is used, to illustrate ‘Dynamically Fetch data from Mysql to (drop down)
select option in Jsp’ :
id City
1 London
2 Bangalore
3 Mumbai
4 Paris
Following codes are used to insert the data in the MySql database. Database used is “City” and username = “root” and password is also set as “root”.
Create Database city;
Use city;
Create table new(id int(4), city varchar(30));
insert into new values(1, 'LONDON');
insert into new values(2, 'MUMBAI');
insert into new values(3, 'PARIS');
insert into new values(4, 'BANGLORE');
Here is the code to Dynamically Fetch data from Mysql to (drop down) select option in Jsp:
<%@ page import="java.sql.*" %>
<%ResultSet resultset =null;%>
<HTML>
<HEAD>
<TITLE>Select element drop down box</TITLE>
</HEAD>
<BODY BGCOLOR=##f89ggh>
<%
try{
//Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection =
DriverManager.getConnection
("jdbc:mysql://localhost/city?user=root&password=root");
Statement statement = connection.createStatement() ;
resultset =statement.executeQuery("select * from new") ;
%>
<center>
<h1> Drop down box or select element</h1>
<select>
<% while(resultset.next()){ %>
<option><%= resultset.getString(2)%></option>
<% } %>
</select>
</center>
<%
//**Should I input the codes here?**
}
catch(Exception e)
{
out.println("wrong entry"+e);
}
%>
</BODY>
</HTML>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…