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

6

例如:

select name from person where id=2;

我想知道这一行是否存在,根据其存在与否执行某些任务。我想使用JDBC实现这个功能。

4个回答

17

使用PreparedStatement来执行这个查询语句,

成功执行查询后,你会得到一个ResultSet实例,通过调用next()方法可以检查是否返回true,如果是则表示有一行被选中。

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

没有明确说明的是,通常情况下您的预处理语句会稍作修改:PreparedStatement pstmt = con.prepareStatement("select name from person where id=?"); pstmt.setInt(1,2); - unigeek

4
   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()返回true;如果游标在任何其他位置或结果集不包含任何行,则返回false。


result.isBeforeFirst() 给出最好的结果! - Evhz

4

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

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

}
else{
  //no next row found

}

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接