使用JDBC獲取select count(*) from table_name
阿新 • • 發佈:2018-11-23
public int getCount() {
int count = 0;
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "select count(*) from table_name";
try {
con=this.getConnection();
if (con!=null) {
ps=con.prepareStatement(sql);
rs=ps.executeQuery();
if(rs.next()) {
count=rs.getInt(1);
System.out.println("count:"+count);
}
}
} catch (Exception e) {
// TODO: handle exception
}
return count;
}
---------------------
還可以這樣:
select count(1) as numb from ...
rs.getInt("numb");
是這樣子的
select count(*) from [table]
rs.next();
int count =rs.getInt(1);
就可以了
Statement stmt = con.createStatement();
ResultSet rs=null;
rs=stmt.executeQuery(sql);
if(rs.next())
count=rs.getInt(1);
不然你取的資料集是無效的,因為rs開始是指向第一組資料之前的