JSP连接数据库,实现新增、修改、删除、查询等操作
时间: 2023-07-10 19:07:32 浏览: 71
JSP连接数据库可以使用Java的JDBC API。以下是一个简单的JSP连接数据库的示例代码,实现了新增、修改、删除、查询等操作:
```jsp
<%@ page import="java.sql.*" %>
<%
// 定义数据库连接信息
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "123456";
// 建立数据库连接
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, username, password);
// 新增数据
stmt = conn.createStatement();
int rows = stmt.executeUpdate("insert into user(name, age) values('Tom', 18)");
out.print(rows + " rows inserted.");
// 修改数据
rows = stmt.executeUpdate("update user set age = 19 where name = 'Tom'");
out.print(rows + " rows updated.");
// 删除数据
rows = stmt.executeUpdate("delete from user where name = 'Tom'");
out.print(rows + " rows deleted.");
// 查询数据
rs = stmt.executeQuery("select * from user");
while (rs.next()) {
String name = rs.getString("name");
int age = rs.getInt("age");
out.print("name: " + name + ", age: " + age + "<br>");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
}
%>
```
在上面的示例中,我们先定义了数据库连接信息,然后使用`Class.forName()`方法加载MySQL的JDBC驱动程序,并通过`DriverManager.getConnection()`方法建立数据库连接。
接下来,我们使用`Statement`对象执行SQL语句,实现了新增、修改、删除、查询等操作。最后,我们在`finally`块中关闭了数据库连接。
需要注意的是,上面的示例代码并没有使用JSP的EL表达式和JSTL标签库,仅作为演示JSP连接数据库的基本原理。在实际开发中,我们应该尽量使用EL表达式和JSTL标签库,以提高代码的可读性和可维护性。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)