如何判断表中是否存在行?

时间:2022-02-12 09:21:58

For example:

例如:

select name from person where id=2;

I wand to know if this row exists, and depending on its existence perform a certain task. I wan to do this using jdbc.

我想知道这一行是否存在,并根据其存在执行某项任务。我想用jdbc做到这一点。

3 个解决方案

#1


13  

Use PreparedStatement to invoke this select query,

使用PreparedStatement调用此选择查询,

After the successful execution of query you would have instance of ResultSet returned, you could check by invoking next() if it returns true it means there was a row selected

成功执行查询后,您将返回ResultSet实例,您可以通过调用next()来检查它是否返回true表示已选中一行

if(resultSet.next()){
   //yes exist
}

#2


4  

The is no hasNext() method in ResultSet. The next() method moves the cursor to the next row and if there is a row then it returns true.

ResultSet中没有hasNext()方法。 next()方法将光标移动到下一行,如果有一行,则返回true。

if(resultSet.next()){
  //do something

}
else{
  //no next row found

}

#3


2  

   Connection conn = DriverManager.getConnection(url , databaseUserName, databasePassword);
            Statement stmt = conn.createStatement();
            ResultSet result = null;           
            result = stmt.executeQuery("select name from person where id=2;");
            if(!result.isBeforeFirst()){
                System.out.println("No Data Found"); //data not exist
            }
           else{
              // data exist
              }   

isBeforeFirst() returns true if the cursor is before the first row; false if the cursor is at any other position or the result set contains no rows

如果光标在第一行之前,isBeforeFirst()返回true;如果光标位于任何其他位置或结果集不包含任何行,则返回false

#1


13  

Use PreparedStatement to invoke this select query,

使用PreparedStatement调用此选择查询,

After the successful execution of query you would have instance of ResultSet returned, you could check by invoking next() if it returns true it means there was a row selected

成功执行查询后,您将返回ResultSet实例,您可以通过调用next()来检查它是否返回true表示已选中一行

if(resultSet.next()){
   //yes exist
}

#2


4  

The is no hasNext() method in ResultSet. The next() method moves the cursor to the next row and if there is a row then it returns true.

ResultSet中没有hasNext()方法。 next()方法将光标移动到下一行,如果有一行,则返回true。

if(resultSet.next()){
  //do something

}
else{
  //no next row found

}

#3


2  

   Connection conn = DriverManager.getConnection(url , databaseUserName, databasePassword);
            Statement stmt = conn.createStatement();
            ResultSet result = null;           
            result = stmt.executeQuery("select name from person where id=2;");
            if(!result.isBeforeFirst()){
                System.out.println("No Data Found"); //data not exist
            }
           else{
              // data exist
              }   

isBeforeFirst() returns true if the cursor is before the first row; false if the cursor is at any other position or the result set contains no rows

如果光标在第一行之前,isBeforeFirst()返回true;如果光标位于任何其他位置或结果集不包含任何行,则返回false