通過以下代碼片段,我試圖運行一個查詢來更新數據或向名爲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");
}
所以我應該怎麼修改代碼,使重複的值將被更新和插入新的價值?