简体   繁体   English

检查是否存在行,否则相应插入

[英]Check if exists row else insert accordingly

I'm trying to check if the database has the row Comment matches according from getComments2. 我试图根据getComments2检查数据库是否具有注释行匹配。

If there exists such row, proceed with the next data checking else it will execute the insert statement 如果存在这样的行,则进行下一个数据检查,否则它将执行insert语句

After I ran this code, it gave me: 运行这段代码后,它给了我:

  1. java.sql.SQLException: Illegal operation on empty result set (When database is empty) or java.sql.SQLException:对空结果集的非法操作(当数据库为空时)或
  2. java.sql.SQLException: After end of result set (When database is filled). java.sql.SQLException:结果集结束后(填充数据库时)。

Code: 码:

String url = "test";
String getComments2 = "test1";
String getTime1 = "test2";
String sqlSelect = "Select comment from predata";
PreparedStatement ps1 = conn.prepareStatement(sqlSelect);
ResultSet rs =  ps1.executeQuery();

boolean exists = false;
while(!rs.last()||(!exists)) {
    rs.next();
    if(rs.getString("Comment").compareTo(getComments2)==0) {
        exists = true;
    }
    if(!exists||rs ==null) {
        PreparedStatement ps = conn.prepareStatement("INSERT into predata (topic,comment,date) VALUES (?,?,?)");
        ps.setString(1, url);
        ps.setString(2, getComments2);
        ps.setString(3, getTime1);
        ps.executeUpdate();
    }
}

rs.last() moves the cursor to the last row. rs.last()将光标移动到最后一行。 Then rs.next() moves it past the last row, so rs.getString("Comment") throws an exception. 然后rs.next()将其移到最后一行,因此rs.getString("Comment")引发异常。

The correct logic should be: 正确的逻辑应该是:

boolean exists = false;
while (rs.next() && !exists) {
    if(rs.getString("Comment").equals(getComments2)) {
        exists = true;
    }
}
if (!exists) {
    PreparedStatement ps = conn.prepareStatement("INSERT into predata (topic,comment,date) VALUES (?,?,?)");
    ps.setString(1, url);
    ps.setString(2, getComments2);
    ps.setString(3, getTime1);
    ps.executeUpdate();
}

You can use Merge in your query itself instead of checking condition in code. 您可以在查询本身中使用Merge ,而不是检查代码中的条件。 Else you can user Insert or Replace in query itself. 否则,您可以在查询本身中使用插入或替换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM