通过以下代码段,我试图运行一个查询,该查询将更新数据或将新数据插入名为JustPinged的表中。该表包含名为NodesThatJustPingedLastPingedAt的列。如果NodesThatJustPinged中已经有一个节点,则更新LastPingedAt中以毫秒为单位的时间。否则,将插入新的node信息。

问题是,以下代码段无法将数据插入数据库的表中。原因是:

boolean duplicateExists = searchToEliminateDuplicates.execute();


返回true开始。 (表最初是空的)为什么此语句返回true?根据documentation,如果第一个结果是ResultSet对象,则返回true;否则,返回true。如果第一个结果是更新计数或没有结果,则返回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");
}


那么我应该如何编辑代码,以便更新重复值并插入新值?

最佳答案

您的searchQuery将返回ResultSet。因此execute方法返回“ true”。尝试改用executeQuery。

因此,您的代码将变为:

String searchQuery = "select NodesThatJustPinged from JustPinged where NodesThatJustPinged = '" + nodeInfo + "'";
    Statement searchToEliminateDuplicates = connection.createStatement();
    ResultSet duplicateExists = searchToEliminateDuplicates.executeQuery(searchQuery);

    if(duplicateExists.next()) {
        // 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");
      }


附言如果使用的是PreparedStatement,则在查询中使用参数并调用ps.setString等。

PPS。不要使用execute()方法。使用executeQuery或executeUpdate。在您不知道查询是INSERT还是UPDATE的情况下使用execute()。

PPPS处理完结果集和语句后,请立即关闭它们。

PPPPS一种更好的方法是在SQL语句中使用count聚合函数,即

从JustPinged中选择count(NodesThatJustPinged),其中NodesThatJustPinged ='“ + nodeInfo +”'“;

现在,您可以检查count是0还是大于1,并相应地分支代码。

07-24 09:37
查看更多