我想检查数据库中是否存在int值。我有两个类,一个我在jdbc连接的类(该方法称为“checkid”):
Statement stmt = null;
String query = SELECT * FROM Table1 WHERE id = ?";
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null){
System.out.println("result set has got something");
while (rs.next())
{
//NOW YOU'RE ON ROW 1
}
} else {
out.println("result set is empty");
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
}
我称之为这种方法的课程,现在我的问题是。如何检查记录是否存在? 我认为它是这样的:
int id = 10;
JDBCClass jdbcClass = new JDBCClass ();
if (jdbcClass.checkid(id) == null)
System.err.println("null");
答案 0 :(得分:1)
你可以尝试这样的事情。如果光标位于第一行之前,isBeforeFirst()
将返回true;
ResultSet rs = stmt.executeQuery(query);
if(!rs.isBeforeFirst()){
System.out.println("result set is empty");
}
else {
System.out.println("Result set is not empty");
}
为了完整起见,你应该改变方法来返回一个布尔值并使用一个准备好的语句,这是一个很好的习惯,以便将来进入。这样的事情可能是最好的解决方案。
public boolean checkId(int id) {
String sql = "Select 1 from MyTable where id = ?";
PreparedStatement ps = dbConn.prepareStatement(sql);
ps.setString(1, id);
ResultSet rs = ps.executeQuery();
return rs.next();
}
答案 1 :(得分:0)
在头等舱,
public ResultSet checkId(int id) {
String sql = "Your query";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, id);
ResultSet rs = ps.executeQuery();
return rs;//return result rs here
}
简单地说,在其他课程中,
ResultSet rs = jdbcClass.checkid(id);
if (rs == null)
System.err.println("null");
else
{
//process the result rs here since record id exists
while(rs.next())
{
//some...
}
}