我正在制作一个网络服务,其中有大量记录,必须更快地将它们插入数据库。
我使用 PreparedStatement
。有什么方法可以更快地插入记录?
数据是动态传入的,因此无法硬编码插入多少数据。我有一个不同的类,它在数据库查询中很常见,我通过我的“Servlet”调用它。
数据库查询代码如下:
public void insertUser_Details(String name,String address) throws Exception {
ps=con.prepareStatement("insert into registration_table(name,address) values(?,?)");
ps.setString(1,name);
ps.setString(2,address);
ps.executeUpdate();
}
最佳答案
假设您在 Employee
中有您的 name
和 address
,现在您需要插入许多 Employee
记录到db,可以使用JDBC批量操作,优化性能。
PreparedStatement ps = con.prepareStatement("INSERT INTO registration_table(name,address) VALUES (?, ?)");
for(Employee employee: employees){
ps.setString(1,employee.getName());
ps.setString(2,employee.getAddress());
ps.addBatch();// add to batch
ps.clearParameters();
}
int[] results = ps.executeBatch();// execute with batch rather than execute many SQL separately.
如果您没有实体对象(员工)来保存数据,您也可以使用数组或集合轻松更改代码来保存数据。
您可以阅读 batch insert in java了解更多信息
关于java - 如何更快地将多条记录插入MySQL,Java?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27223045/