jdbc预处理增删改查语句
时间: 2024-12-11 19:13:29 浏览: 10
JDBC(Java Database Connectivity)是Java语言中用于执行SQL语句的标准API。预处理语句(PreparedStatement)是JDBC中的一个重要特性,它允许在执行SQL语句之前,先对其进行预编译,从而提高执行效率并防止SQL注入攻击。
以下是使用JDBC预处理语句进行增删改查(CRUD)操作的示例:
### 1. 插入数据(Create)
```java
String sql = "INSERT INTO users (username, password) VALUES (?, ?)";
try (Connection conn = DriverManager.getConnection(url, username, password);
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, "john_doe");
pstmt.setString(2, "password123");
int rowsAffected = pstmt.executeUpdate();
System.out.println(rowsAffected + " row(s) inserted.");
} catch (SQLException e) {
e.printStackTrace();
}
```
### 2. 查询数据(Read)
```java
String sql = "SELECT * FROM users WHERE username = ?";
try (Connection conn = DriverManager.getConnection(url, username, password);
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, "john_doe");
try (ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
int id = rs.getInt("id");
String username = rs.getString("username");
String password = rs.getString("password");
System.out.println("ID: " + id + ", Username: " + username + ", Password: " + password);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
```
### 3. 更新数据(Update)
```java
String sql = "UPDATE users SET password = ? WHERE username = ?";
try (Connection conn = DriverManager.getConnection(url, username, password);
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, "newpassword");
pstmt.setString(2, "john_doe");
int rowsAffected = pstmt.executeUpdate();
System.out.println(rowsAffected + " row(s) updated.");
} catch (SQLException e) {
e.printStackTrace();
}
```
### 4. 删除数据(Delete)
```java
String sql = "DELETE FROM users WHERE username = ?";
try (Connection conn = DriverManager.getConnection(url, username, password);
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, "john_doe");
int rowsAffected = pstmt.executeUpdate();
System.out.println(rowsAffected + " row(s) deleted.");
} catch (SQLException e) {
e.printStackTrace();
}
```
### 优点
1. **防止SQL注入**:预处理语句可以有效防止SQL注入攻击,因为输入参数会被视为字面值而不是可执行的SQL代码。
2. **提高性能**:预编译的SQL语句可以重复使用,减少了数据库的编译时间,从而提高了性能。
3. **代码可读性**:使用预处理语句可以使代码更加简洁和可读。
阅读全文