mysql jdbc驱动 批量更新_jdbc批量插入,删除,更新
时间: 2023-07-07 21:09:47 浏览: 185
JDBC提供了批量操作的支持,可以通过一次数据库连接,执行多个相似的数据库操作,从而提高数据库操作的效率。下面是JDBC批量操作的示例代码:
1. 批量插入数据:
```java
Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
String sql = "INSERT INTO student (name, age, gender) VALUES ('Tom', 18, 'M')";
stmt.addBatch(sql);
sql = "INSERT INTO student (name, age, gender) VALUES ('Lucy', 20, 'F')";
stmt.addBatch(sql);
sql = "INSERT INTO student (name, age, gender) VALUES ('Jack', 19, 'M')";
stmt.addBatch(sql);
int[] result = stmt.executeBatch(); // 执行批量插入
```
2. 批量更新数据:
```java
Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
String sql = "UPDATE student SET age = 20 WHERE gender = 'M'";
stmt.addBatch(sql);
sql = "UPDATE student SET age = 22 WHERE gender = 'F'";
stmt.addBatch(sql);
int[] result = stmt.executeBatch(); // 执行批量更新
```
3. 批量删除数据:
```java
Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
String sql = "DELETE FROM student WHERE age < 18";
stmt.addBatch(sql);
sql = "DELETE FROM student WHERE age > 22";
stmt.addBatch(sql);
int[] result = stmt.executeBatch(); // 执行批量删除
```
需要注意的是,批量操作的语句必须是相同的类型,例如,不能混合插入和更新操作。同时,批量操作也可能会受到数据库的限制,例如,数据库有可能限制一次批量操作的数量,需要根据实际情况进行调整。
阅读全文