我想知道在创建另一个表之前是否存在一个表是否存在,是否有任何方法可以在执行命令后将结果保存在变量中,我正在使用此代码,但即使表不存在,它也只给出 true .
public static boolean checkBefore(){
boolean r = false;
try{
query = "SELECT COUNT(*)FROM information_schema.tables WHERE table_schema = 'sms' AND table_name = 'auth';";
con = connectsms();
st = con.createStatement();
ResultSet rs = st.executeQuery(query);
r = rs.next();
}catch(SQLException e){
JOptionPane.showMessageDialog(errorMsg,"Exeption Fount: "+e,"Opps! Exception Found in checkBefore()",JOptionPane.ERROR_MESSAGE);
}
System.out.println(r);
return r;
}
最佳答案
每个 JDBC 指南都会告诉您,执行查询后,您需要调用 next()
前进到下一行/第一行,然后调用 getter 方法来检索该行的列值.
使用聚合函数(COUNT
、MIN
、MAX
等)而不使用 GROUP BY
子句的查询将始终只返回一行,因此对于此类查询,您无需检查 next()
的返回值。对于几乎所有其他查询,您都可以这样做。
当调用返回资源的 JDBC 方法时,您应该使用 try-with-resources 来确保这些资源被正确清理。
查询字符串不需要以 ;
分号结尾。
所有这意味着您的代码应该是:
public static boolean checkBefore() {
String sql = "SELECT COUNT(*)" +
" FROM information_schema.tables" +
" WHERE table_schema = 'sms'" +
" AND table_name = 'auth'";
try ( Connection con = connectsms();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
) {
rs.next(); // exactly one row returned, so next() always returns true here
int count = rs.getInt(1); // get value from first column
System.out.println("count = " + count);
return (count != 0);
} catch (SQLException e) {
JOptionPane.showMessageDialog(errorMsg, "Exeption Fount: " + e,
"Opps! Exception Found in checkBefore()",
JOptionPane.ERROR_MESSAGE);
return 0;
}
}
关于java - 如果可能的话,如何将 MySQL 查询结果保存在 int 变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59815366/