JDBC插入多行 [英] JDBC insert multiple rows

查看:320
本文介绍了JDBC插入多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在使用批处理:

 查询字符串=INSERT INTO表(编号,名称,值)VALUES(,???);
preparedStatement PS =连接prepareStatement(查询)。
对于(录音记录:记录){
    ps.setInt(1,record.id);
    ps.setString(2,record.name);
    ps.setInt(3,record.value);
    ps.addBatch();
}
ps.executeBatch();

我只是想知道,如果上述code是等效于下面code。如果不是,这是更快?

 查询字符串=INSERT INTO表(编号,名称,值)值;
对于(录音记录:记录){
    查询+ =(+ record.id +,+ record.name +',+ record.value +);
}
查询= query.substring(1,query.length() - 1);
preparedStatement PS =连接prepareStatement(查询)。
ps.executeUpdate();


解决方案

首先,与查询字符串连接你不仅失去了类型转换原产于preparedStatement方法,但你也可以得到容易受到恶意code。在数据库中执行。

二,preparedStatements是$ P $在非常数据库本身pviously缓存,这已经给出了简单的陈述了很好的性能提升。

I am now using batch:

String query = "INSERT INTO table (id, name, value) VALUES (?, ?, ?)";
PreparedStatement ps = connection.prepareStatement(query);            
for (Record record : records) {
    ps.setInt(1, record.id);
    ps.setString(2, record.name);
    ps.setInt(3, record.value);
    ps.addBatch();
}
ps.executeBatch();

I am just wondering if the above code is equivalent to the following code. If not, which is faster?

String query = "INSERT INTO table (id, name, value) VALUES ";
for (Record record : records) {
    query += "(" + record.id + ",'" + record.name + "'," + record.value + "),";
}
query = query.substring(1, query.length() - 1);
PreparedStatement ps = connection.prepareStatement(query);
ps.executeUpdate();

解决方案

First of all, with query string concatenation you not only lose the type conversion native to PreparedStatement methods, but you also get vulnerable to malicious code being executed in the database.

Second, PreparedStatements are previously cached in the very database itself, and this already gives a very good performance improvement over plain Statements.

这篇关于JDBC插入多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆