次のスニペットを使用して、データを更新するか、という名前のテーブルに新しいデータを挿入するクエリを実行しようとしていますJustPinged。NodesThatJustPingedテーブルには、およびという名前の列が含まれていますLastPingedAt。にすでにノードがある場合はNodesThatJustPinged、ミリ秒単位の時間LastPingedAtが更新されます。それ以外の場合は、新しいnode情報が挿入されます。
問題は、次のスニペットがデータベースのテーブルにデータを挿入できないことです。理由は次のとおりです。
boolean duplicateExists = searchToEliminateDuplicates.execute();
最初に戻りますtrue。(最初はテーブルが空です)このステートメントがtrueを返すのはなぜですか?ドキュメントによると、最初の結果が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");
}
では、重複する値が更新され、新しい値が挿入されるように、コードをどのように編集する必要がありますか?