在eclipse中使用jsp编写数据库查询程序,要求生成窗口,并使用jdbc连接数据库bus,有搜索按钮,可以在窗口文本框输入想要的数据,点击搜索按钮即可搜索数据库中的数据
时间: 2024-02-01 16:16:01 浏览: 30
首先,需要在Eclipse中创建一个Dynamic Web Project,然后在WebContent目录下创建一个名为“index.jsp”的JSP页面,用于生成窗口和搜索按钮。以下是示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>查询页面</title>
</head>
<body>
<h1>查询页面</h1>
<form method="post" action="query.jsp">
<label>查询条件:</label>
<input type="text" name="keyword">
<input type="submit" value="搜索">
</form>
</body>
</html>
```
接下来,在WebContent目录下创建一个名为“query.jsp”的JSP页面,用于处理搜索请求并连接数据库进行查询。以下是示例代码:
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>查询结果</title>
</head>
<body>
<h1>查询结果</h1>
<table border="1">
<tr>
<th>车次</th>
<th>起点站</th>
<th>终点站</th>
<th>出发时间</th>
<th>到达时间</th>
<th>票价</th>
</tr>
<%
String keyword = request.getParameter("keyword");
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
// 连接数据库
String url = "jdbc:mysql://localhost:3306/bus";
String user = "root";
String password = "123456";
conn = DriverManager.getConnection(url, user, password);
// 执行查询
String sql = "SELECT * FROM schedule WHERE train_number LIKE '%"
+ keyword + "%' OR start_station LIKE '%" + keyword
+ "%' OR end_station LIKE '%" + keyword + "%'";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
// 显示查询结果
while (rs.next()) {
out.println("<tr>");
out.println("<td>" + rs.getString("train_number") + "</td>");
out.println("<td>" + rs.getString("start_station") + "</td>");
out.println("<td>" + rs.getString("end_station") + "</td>");
out.println("<td>" + rs.getString("departure_time") + "</td>");
out.println("<td>" + rs.getString("arrival_time") + "</td>");
out.println("<td>" + rs.getDouble("ticket_price") + "</td>");
out.println("</tr>");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
try {
if (rs != null)
rs.close();
if (stmt != null)
stmt.close();
if (conn != null)
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
%>
</table>
</body>
</html>
```
以上代码通过JDBC连接MySQL数据库,执行查询语句,并将查询结果显示在页面上。请根据实际情况修改数据库连接信息和查询语句。