通过以下代码片段,我试图运行一个查询来更新数据或向名为JustPinged
的表中插入新数据。该表包含名为NodesThatJustPinged
和LastPingedAt
的列。如果在NodesThatJustPinged
中已经有节点,则LastPingedAt
中的时间以毫秒为单位进行更新。否则会插入一个新的node
信息。为什么execute()在空表上返回true?
的问题是,下面的代码片段是无法将数据插入到数据库中的表。原因是该语句:
boolean duplicateExists = searchToEliminateDuplicates.execute();
回报true
开始。 (最初这个表是空的)为什么这个语句返回true?根据documentation,如果第一个结果是ResultSet对象,则返回;如果第一个结果是更新计数或没有结果,则为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");
}
所以我应该怎么修改代码,使重复的值将被更新和插入新的价值?