gpt4 book ai didi

java - 使用jsp搜索数据

转载 作者:行者123 更新时间:2023-12-01 12:48:59 24 4
gpt4 key购买 nike

我想在sql server数据库中搜索记录,然后使用jsp将其显示在网页中。我该怎么做,请帮助我。我的代码也给出如下。谢谢

<%
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/mydb","root","root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM test where firstName = ?");
while (rs.next()){
%>
<tr bgcolor="#Abc">
<td> <%=rs.getString("firstName")%> </td>
<td><%=rs.getString("lastname")%></td>
</tr>
<%
}
}catch (Exception ex){
System.out.println(ex.getMessage());
}
%>

最佳答案

您需要指定要查询的“名字”。

假设它作为 URL 中的参数传递 (http://localhost/myapp/mypage.jsp?firstName=Nick),这应该可以解决问题:

<%

Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;

try
{
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","root");

statement = connection.prepareStatement("SELECT firstName, lastName FROM test WHERE firstName = ?");
statement.setString(1, request.getParameter("firstName"));

resultSet = statement.executeQuery();

while (resultSet.next())
{
%>

<tr>
<td><%= resultSet.getString(1) %></td>
<td><%= resultSet.getString(2) %></td>
</tr>

<%
}
}
finally
{
if (resultSet != null) result.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
}
%>

注意:

关于java - 使用jsp搜索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24403796/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com