java插入多条数据sql
时间: 2024-04-15 07:31:05 浏览: 10
你可以使用以下代码示例来插入多条数据到数据库中:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class InsertMultipleDataExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "yourusername";
String password = "yourpassword";
try (Connection conn = DriverManager.getConnection(url, username, password)) {
String sql = "INSERT INTO mytable (column1, column2) VALUES (?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
// 创建数据数组
String[][] data = {
{"value1", "value2"},
{"value3", "value4"},
// 添加更多数据...
};
for (String[] rowData : data) {
statement.setString(1, rowData[0]);
statement.setString(2, rowData[1]);
statement.addBatch();
}
int[] rowsInserted = statement.executeBatch();
System.out.println("插入的行数:" + rowsInserted.length);
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
```
在上述示例中,我们使用了`PreparedStatement`来预编译SQL语句,并通过循环将多条数据的值设置到对应的占位符中,然后将其添加到批处理中。最后,通过调用`executeBatch()`方法执行批处理,并返回插入的行数。
请注意,你需要根据你的数据库和表结构修改示例代码中的URL、用户名、密码、表名和列名。同时,你可以根据需要调整数据数组以插入更多的数据。