MySQL 如何从数据库中获取下拉值并在jsp中显示

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22550913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 20:16:52  来源:igfitidea点击:

How to fetch the dropdown values from database and display in jsp

mysqljsp

提问by user2585622

I have two dropdowns in jsp and have to get dropdown list from database and show it in jsp. I am using jsp for the first time . Can you give me an idea to fetch the dropdown list from database and display the values in jsp dropdown element.Thanks in advance

我在jsp中有两个下拉列表,必须从数据库中获取下拉列表并在jsp中显示它。我是第一次使用jsp。你能给我一个从数据库中获取下拉列表并在jsp下拉元素中显示值的想法吗?提前谢谢

回答by jmail

how to fetch the dropdown values from database and display in jsp:

如何从数据库中获取下拉值并在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 :

从 Mysql 动态获取数据到(下拉)在 Jsp 中选择选项。这篇文章说明了从 mysql 数据库中获取数据并显示在 Jsp 中的 select 选项元素中。在阅读这篇文章之前,您应该了解以下文章,即:

How to Connect Mysql database to jsp.

如何将Mysql数据库连接到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)

如何在MySql中创建数据库并将数据插入数据库。使用以下数据库,来说明'Dynamically Fetch data from Mysql to (drop down)

select option in Jsp' :

在 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”.

以下代码用于在MySql数据库中插入数据。使用的数据库是“City”,用户名=“root”,密码也设置为“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:

这是从 Mysql 动态获取数据到 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>

enter image description here

在此处输入图片说明

回答by Wundwin Born

You can learn some tutorials for JSP page direct access database (mysql) here

你可以学习JSP页面直接访问数据库(MySQL的)一些教程在这里

Notes:

笔记:

  • import sql tag library in jsp page

    <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>

  • then set datasource on page

    <sql:setDataSource var="ds" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://<yourhost>/<yourdb>" user="<user>" password="<password>"/>
    
  • Now query what you want on page

    <sql:query dataSource="${ds}" var="result"> //ref  defined 'ds'
        SELECT * from <your-table>;
    </sql:query>
    
  • Finally you can populate dropdowns on page using c:forEachtag to iterate result rows in selectelement

    <c:forEach var="row" items="${result.rows}"> //ref set var 'result' <option value='<c:out value="${row.key}"/>'><c:out value="${row.value}"/</option> </c:forEach>

  • 在jsp页面中导入sql标签库

    <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>

  • 然后在页面上设置数据源

    <sql:setDataSource var="ds" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://<yourhost>/<yourdb>" user="<user>" password="<password>"/>
    
  • 现在在页面上查询您想要的内容

    <sql:query dataSource="${ds}" var="result"> //ref  defined 'ds'
        SELECT * from <your-table>;
    </sql:query>
    
  • 最后,您可以使用c:forEach标签在页面上填充下拉列表以迭代select元素中的结果行

    <c:forEach var="row" items="${result.rows}"> //ref set var 'result' <option value='<c:out value="${row.key}"/>'><c:out value="${row.value}"/</option> </c:forEach>

回答by Mahmoud Badawy

I made this in my code to do that

我在我的代码中做了这个

note: I am a beginner.

注意:我是初学者。

It is my jsp code.

这是我的jsp代码。

<%
java.sql.Connection Conn = DBconnector.SetDBConnection(); /* make connector as you make in your code */
Statement st = null;
ResultSet rs = null;
st = Conn.createStatement();
rs = st.executeQuery("select * from department"); %>
<tr> 
    <td> 
        Student Major  : <select name ="Major">
        <%while(rs.next()){ %>
        <option value="<%=rs.getString(1)%>"><%=rs.getString(1)%></option>
                        <%}%>           
                         </select> 
   </td> 

回答by Pransh Tiwari

  1. Make the database connection and retrieve the query result.
  2. Traverse through the result and display the query results.
  1. 建立数据库连接并检索查询结果。
  2. 遍历结果并显示查询结果。

The example code below demonstrates this in detail.

下面的示例代码详细说明了这一点。

<%@page import="java.sql.*, java.io.*,listresult"%> //import the required library

<%

String label = request.getParameter("label"); // retrieving a variable from a previous page

Connection dbc = null; //Make connection to the database
Class.forName("com.mysql.jdbc.Driver");
dbc = DriverManager.getConnection("jdbc:mysql://localhost:3306/works", "root", "root");
if (dbc != null) 
{
    System.out.println("Connection successful");
}

ResultSet rs = listresult.dbresult.func(dbc, label); //This function is in the end. The function is defined in another package- listresult

%>

<form name="demo form" method="post">

    <table>
        <tr>
            <td>
                Label Name:
            </td>

            <td>
                <input type="text" name="label" value="<%=rs.getString("labelname")%>">
            </td>

            <td>
                <select name="label">
                <option value="">SELECT</option>

                <% while (rs.next()) {%>

                    <option value="<%=rs.getString("lname")%>"><%=rs.getString("lname")%>
                    </option>

                <%}%>
                </select>
            </td>
        </tr>
    </table>

</form>

//The function:

public static ResultSet func(Connection dbc, String x)
{
    ResultSet rs = null;
    String sql;
    PreparedStatement pst;
    try
    {
        sql = "select lname from demo where label like '" + x + "'";
        pst = dbc.prepareStatement(sql);
        rs = pst.executeQuery();
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
        String sqlMessage = e.getMessage();
    }
    return rs;
}

I have tried to make this example as detailed as possible. Do ask if you have any queries.

我试图使这个例子尽可能详细。如果您有任何疑问,请询问。