我有一个带有表'admin'的数据库。但是目前只是创建一个没有任何值的表。表的列是user_name和password。我的目的是检查表是否为空。我正在使用mysql database.I尝试了以下代码,但失败了。请帮助我。
public void nullCheck() {
PreparedStatement stmt = null;
ResultSet rs = null;
String qry = "SELECT * From admin ";
try {
stmt = (PreparedStatement) conn.prepareStatement(qry);
rs = stmt.executeQuery();
boolean empty = true;
while( rs.next() ) {
// ResultSet processing here
empty = false;
}
if( empty ) {
Util.showWarningMessageDialog("null");
}
} catch (SQLException ex) {
Logger.getLogger(RemoveFaculty.class.getName()).log(Level.SEVERE, null, ex);
}
}
如果只需要检查表,则应使用查询:
String qry = "SELECT count(*) From admin ";
为了获得更好的性能。并从ResultSet获取行数以检查表是否为空。
int count=0;
while( rs.next() )
{
count=rs.getInt("count");
}
尝试此代码,我认为这可以做到。
public void nullCheck() {
PreparedStatement stmt = null;
ResultSet rs = null;
String qry = "SELECT * From admin ";
try {
stmt = (PreparedStatement) conn.prepareStatement(qry);
rs = stmt.executeQuery();
int getRow = rs.getRow();
if(getRow == 0){
// if equal to 0 then the table is nullbla bla bla
}
} catch (SQLException ex) {
Logger.getLogger(RemoveFaculty.class.getName()).log(Level.SEVERE, null, ex);
}
}