我是SQL的新手。我的目标是创建一个程序,该程序应检查某个表是否具有某个值。我已经写了这种方法
public boolean existString(final String query) {
try {
final Statement statement = this.conn.createStatement();
result = statement.executeQuery(query);
return true;
} catch(SQLException e) {
e.printStackTrace();
return false;
}
}
如您所见,它是一种执行SQL语句的方法。我认为这可能是正确的说法:
String query = "select * from table where column1 = 'checkvalue'"; // of course i need to replace table and column and checkvalue
但是在执行此语句后,如何证明它是否成功(查询返回了什么内容)?如果该语句在执行后将返回某些内容,则可以轻松地使用if语句进行检查。
如果没有从数据库返回的行,则SQL语句可以成功返回,因此SQLException
如果查询正确但不匹配,则使用a 不会对您有帮助。
public boolean existString(final String query) {
try {
final Statement statement = this.conn.createStatement();
result = statement.executeQuery(query);
return result.next();
} catch(SQLException e) {
e.printStackTrace();
return false;
}
}
您应该利用以下事实:result.next()
尝试将结果指针移到下一行并返回是否有要返回的行。这样,如果成功并且有结果ir返回true
,而成功但没有结果,则返回false
。如果出了点问题,您将在异常处理过程中得到充分的休息。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句