【发布时间】:2013-01-04 05:49:31
【问题描述】:
通过以下 sn-p,我正在尝试运行一个查询,该查询要么更新数据,要么将新数据插入名为 JustPinged 的表中。该表包含名为NodesThatJustPinged 和LastPingedAt 的列。如果NodesThatJustPinged 中已经有一个节点,那么LastPingedAt 中的时间(以毫秒为单位)将被更新。否则插入新的node 信息。
问题是,下面的 sn -p 无法将数据插入到数据库的表中。原因是声明:
boolean duplicateExists = searchToEliminateDuplicates.execute();
返回 true 开始。 (最初表是空的)为什么这个语句返回true?根据documentation,如果第一个结果是 ResultSet 对象,则返回 true;如果第一个结果是更新计数或没有结果,则返回 false。 所以这里的布尔值应该包含一个 false 值。但它包含一个true 值,因此if 语句始终有效。 (在if 部分,更新查询在没有任何更新时有效!)
String searchQuery = "select NodesThatJustPinged from JustPinged where NodesThatJustPinged = '" + nodeInfo + "'";
PreparedStatement searchToEliminateDuplicates = connection.prepareStatement(searchQuery);
boolean duplicateExists = searchToEliminateDuplicates.execute();
if(duplicateExists) {
// update the LastPingedAt column in the JustPinged table
String updateQuery = "update JustPinged set LastPingedAt='" + pingedAt + "' where NodesThatJustPinged = '" + nodeInfo + "'";
PreparedStatement updateStatement = connection.prepareStatement(updateQuery);
updateStatement.executeUpdate();System.out.println("If statement");
} else {
// make a new entry into the database
String newInsertionQuery = "insert into JustPinged values('" + nodeInfo + "','" + pingedAt + "')";
PreparedStatement insertionStatement = connection.prepareStatement(newInsertionQuery);
insertionStatement.executeUpdate();System.out.println("else statement");
}
那么我应该如何编辑代码,以便更新重复值并插入新值?
【问题讨论】: