jsp页面连接数据库代码命令
时间: 2024-10-24 14:02:08 浏览: 19
JSP页面连接数据库通常涉及使用Java的 JDBC (Java Database Connectivity) API。以下是基本步骤:
1. **导入必要的库**:
```jsp
<%@ taglib prefix="jdbc" uri="http://java.sun.com/jsp/jdbc" %>
```
2. **创建数据库连接(Connection)对象**:
```jsp
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "username";
String password = "password";
try {
// 使用DriverManager.getConnection()方法建立连接
conn = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
// 处理连接失败的情况
e.printStackTrace();
}
```
3. **声明Statement、PreparedStatement或CallableStatement**:
- Statement(非预编译,安全性较低)
```jsp
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
```
- PreparedStatement(预编译,更安全,能防止SQL注入攻击)
```jsp
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM mytable WHERE id = ?");
pstmt.setInt(1, 1); // 设置参数
rs = pstmt.executeQuery();
```
- CallableStatement(用于存储过程和函数调用)
```jsp
CallableStatement cs = conn.prepareCall("{call my StoredProc(?)}");
cs.setInt(1, 1);
rs = cs.executeQuery();
```
4. **处理查询结果(如遍历ResultSet)**:
```jsp
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
// 处理数据...
}
```
5. **关闭资源**:
```jsp
try {
rs.close();
pstmt.close(); // 或者stmt.close()
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
```
阅读全文