Java代码实现sqlserver的batch 插入数据
时间: 2024-09-28 07:12:44 浏览: 34
在Java中,我们可以使用JDBC (Java Database Connectivity) 来执行SQL Server的批量插入操作。首先,你需要添加JDBC驱动到项目中,比如`mssql-jdbc`。以下是基本的步骤:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class BatchInsertExample {
private static final String DB_URL = "jdbc:jtds:sqlserver://localhost:1433;databaseName=your_database";
private static final String USER = "your_username";
private static final String PASS = "your_password";
public static void main(String[] args) {
try {
// 加载数据库驱动
Class.forName("net.sourceforge.jtds.jdbc.Driver");
// 获取连接
Connection connection = DriverManager.getConnection(DB_URL, USER, PASS);
// 创建批量插入的PreparedStatement
String sql = "INSERT INTO your_table (column1, column2, ...) VALUES (?, ?, ...)";
PreparedStatement preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); // SET RETURN_GENERATED_KEYS if you need auto-increment primary key
// 数据准备,可以是一个数组或者集合
Object[][] data = {{"value1", "value2"}, {"value3", "value4"}};
for (Object[] rowData : data) {
preparedStatement.setObject(1, rowData[0]); // 第一个参数替换为实际列数
preparedStatement.setObject(2, rowData[1]);
// 更多列...
preparedStatement.addBatch();
}
// 执行批量插入
int[] results = preparedStatement.executeBatch();
// 处理生成的主键(如果需要)
ResultSet generatedKeys = preparedStatement.getGeneratedKeys();
while (generatedKeys.next()) {
Long id = generatedKeys.getLong(1);
System.out.println("Inserted row with ID: " + id);
}
generatedKeys.close();
// 关闭预处理语句和连接
preparedStatement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
阅读全文