java+myslq批量添加学生信息代码
时间: 2023-07-30 13:10:27 浏览: 72
可以参考以下 Java 代码实现批量添加学生信息到 MySQL 数据库:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class BatchInsertStudents {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "root";
String password = "123456";
String insertSql = "INSERT INTO students (name, age, gender) VALUES (?, ?, ?)";
try (Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement pstmt = conn.prepareStatement(insertSql)) {
conn.setAutoCommit(false);
// 批量插入 100 条学生信息
for (int i = 1; i <= 100; i++) {
pstmt.setString(1, "student" + i);
pstmt.setInt(2, i % 20 + 18); // 年龄为 18 到 37 岁
pstmt.setString(3, i % 2 == 0 ? "male" : "female");
pstmt.addBatch();
}
int[] result = pstmt.executeBatch();
conn.commit();
System.out.println("共插入 " + result.length + " 条学生信息");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
上述代码中,我们使用了 `PreparedStatement` 对象进行 SQL 语句的预编译和参数化,提高了插入效率。同时,我们使用 `addBatch()` 方法添加批量操作的 SQL 语句,最后使用 `executeBatch()` 方法执行批量操作。为了保证数据的一致性,我们还需要关闭自动提交事务,并在插入完成后手动提交事务。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](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)