java数据库增删改查的预处理
时间: 2023-08-19 15:04:49 浏览: 93
Java中使用预处理语句可以有效地防止SQL注入攻击,同时也可以提高SQL的执行效率。以下是Java数据库增删改查的预处理语句示例:
1. 插入数据
```java
String sql = "INSERT INTO table_name (column1, column2, column3) VALUES (?, ?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, value1);
statement.setInt(2, value2);
statement.setDouble(3, value3);
int rowsInserted = statement.executeUpdate();
```
2. 更新数据
```java
String sql = "UPDATE table_name SET column1 = ?, column2 = ?, column3 = ? WHERE id = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, value1);
statement.setInt(2, value2);
statement.setDouble(3, value3);
statement.setInt(4, id);
int rowsUpdated = statement.executeUpdate();
```
3. 删除数据
```java
String sql = "DELETE FROM table_name WHERE id = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, id);
int rowsDeleted = statement.executeUpdate();
```
4. 查询数据
```java
String sql = "SELECT * FROM table_name WHERE column1 = ? AND column2 = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, value1);
statement.setInt(2, value2);
ResultSet result = statement.executeQuery();
while (result.next()) {
// 处理查询结果
}
```
阅读全文