if (!knowledge.isEmpty()) {
Iterator<Entry<String, String>> classnmValsItrKW = knowledge
.entrySet().iterator();
while (classnmValsItrKW.hasNext()) {
Entry<String, String> p1 = classnmValsItrKW.next();
String nm = p1.getKey();
String val = p1.getValue();
String query3 = "insert into namevalue(seqid, name, value) values("
+ seqId + ",'" + nm + "','" + val + "')";
//System.out.println("Insert query: " + query3);
st = connect.createStatement();
st.executeUpdate(query3);
}
}
&#34;知识&#34;是哈希表,我存储了名称值对,我想插入到数据库中。但是对于while循环插入查询的每次迭代都会被触发。我认为效率低下。如何通过仅触发插入查询一次插入多行?
答案 0 :(得分:3)
在http://www.mkyong.com/jdbc/jdbc-preparedstatement-example-batch-update/
找到此示例dbConnection.setAutoCommit(false);//commit trasaction manually
String insertTableSQL = "INSERT INTO DBUSER"
+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
+ "(?,?,?,?)";
PreparedStatement = dbConnection.prepareStatement(insertTableSQL);
preparedStatement.setInt(1, 101);
preparedStatement.setString(2, "mkyong101");
preparedStatement.setString(3, "system");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
preparedStatement.addBatch();
preparedStatement.setInt(1, 102);
preparedStatement.setString(2, "mkyong102");
preparedStatement.setString(3, "system");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
preparedStatement.addBatch();
preparedStatement.executeBatch();
dbConnection.commit();
注意强> 批量更新不仅限于Insert语句,它也适用于Update和Delete语句。
答案 1 :(得分:1)
如果您不必担心SQL注入意味着您没有获得任何用户数据,那么您可以试试这个,
if (!knowledge.isEmpty()) {
Iterator<Entry<String, String>> classnmValsItrKW = knowledge
.entrySet().iterator();
StringBuilder query3 = new StringBuilder("insert into namevalue(seqid, name, value) values ");
while (classnmValsItrKW.hasNext()) {
Entry<String, String> p1 = classnmValsItrKW.next();
String nm = p1.getKey();
String val = p1.getValue();
query3.append("("+ seqId + ",'" + nm + "','" + val + "'),");
//System.out.println("Insert query: " + query3);
st = connect.createStatement();
st.executeUpdate(query3);
}
query3.setLength(query3.length() - 1);
}
这将生成具有多个值的插入查询,即
insert into some_table(a, b) values (a1, b1), (a2, b2)...
注意:此处query3
为StringBuilder
,执行时请query3.toString()
。
答案 2 :(得分:0)