繁体   English   中英

Java中的SQL转义和批量插入

[英]SQL-Escaping and bulk-insert in Java

我的目标是批量插入查询中的sql转义。 例如:

INSERT INTO log VALUES (0,5,-7,'str'), (4,0,0,'str'), (0,0,0,'str');

该代码每30秒在表中插入约100-200条记录。 (日志池)。
我没有找到使用PreparedStatement进行批量插入的方法,因此我不得不通过StringBuilder手动构建该查询。
但我不知道如何转义字符串,真的不希望应用类似kludge-fixes(通过正则表达式替换等引号)的方法。

有什么方便的方法吗?

到目前为止,我知道两种方法。

第一种方式

Its insert record one by one

final String sql = "INSERT INTO tablename(columnname) Values(?)";

PreparedStatement statement = connection.prepareStatement(sql);

while (condition) {
statement.setString(1,value);
statement.executeUpdate();
}

第二路

它将所有记录作为批量插入插入

final String sql = "INSERT INTO tablename(columnname) Values(?)";

PreparedStatement statement = connection.prepareStatement(sql);

while (condition) {
statement.setString(1,value);
statement.addBatch();
}

statement.executeBatch();

您需要使用PreparedStatement并可能使用批处理插入。 参见http://www.exampledepot.com/egs/java.sql/BatchUpdate.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM