java preparedStatement.executeUpdate()只插入最后一行

时间:2015-03-02 17:18:45

标签: java sql insert

这是我的代码:

String insertQuery = "INSERT INTO Links(PageId, LinkId) values(?, ?)";
PreparedStatement preparedStatement = con.prepareStatement(insertQuery);
Vector<String> links = page.getLinks();    
for (String string : links) {       
    Concept c = dbpedia.findConceptbyTitle(string);                     
    if (c != null) {
        preparedStatement.setInt(1, Integer.parseInt(page.getID()));
        preparedStatement.setInt(2, c.id);
    }    
}
preparedStatement.executeUpdate();

奇怪的是,当我在executeUpdate之后设置断点时,只在SQL表中插入了最后一行!

2 个答案:

答案 0 :(得分:2)

添加preparedStatement.addBatch();在你离开你的循环之前。

并替换preparedStatement.executeUpdate(); with preparedStatement.executeBatch();.

答案 1 :(得分:1)

每次只执行最后一次操作时,您都会覆盖参数。使用batch- Statement: http://www.mkyong.com/jdbc/jdbc-preparedstatement-example-batch-update/

Bulk insert in Java using prepared statements batch update