jsp与数据库交互
时间: 2023-08-13 12:03:08 浏览: 62
JSP 与数据库交互的一般步骤如下:
1. 导入 JDBC 驱动程序,加载驱动。
2. 建立与数据库的连接。
3. 创建 Statement 或 PreparedStatement 对象,用于向数据库发送 SQL 语句。
4. 执行 SQL 语句,得到结果集。
5. 处理结果集,将结果展示到页面上。
6. 关闭结果集、Statement 或 PreparedStatement 对象、数据库连接等资源。
以下是一个简单的 JSP 与 MySQL 数据库交互的示例代码:
```jsp
<%@ page import="java.sql.*" %>
<html>
<head>
<title>JSP 数据库操作示例</title>
</head>
<body>
<%
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 加载 JDBC 驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 建立与数据库的连接
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "root";
conn = DriverManager.getConnection(url, user, password);
// 创建 Statement 对象
stmt = conn.createStatement();
// 执行 SQL 语句
String sql = "SELECT * FROM users";
rs = stmt.executeQuery(sql);
// 处理结果集
while (rs.next()) {
out.println(rs.getString("id") + " " + rs.getString("name") + "<br/>");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭结果集、Statement 和数据库连接等资源
if (rs != null) {
try { rs.close(); } catch (SQLException e) { e.printStackTrace(); }
}
if (stmt != null) {
try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); }
}
if (conn != null) {
try { conn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
%>
</body>
</html>
```
在这个示例中,我们首先加载了 MySQL 的 JDBC 驱动程序,然后建立了与数据库的连接,并创建了一个 Statement 对象,用于执行 SQL 语句。执行 SQL 语句后,我们遍历了结果集,并将结果展示在页面上。最后,我们关闭了结果集、Statement 对象和数据库连接等资源。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)