Monday, April 21, 2008

Get num of rows in ResultSet -JDBC

public static void main(String[] args)

{

System.out.println("Count records example using prepared statement!");

Connection con = null;

int records = 0; try{

Class.forName ("com.mysql.jdbc.Driver").newInstance ();

con = DriverManager.getConnection ("jdbc:mysql://localhost/adportal", "root", "admin");

con.setAutoCommit(true);

try{

String sql = "SELECT COUNT(*) FROM postmessage";

PreparedStatement prest = con.prepareStatement(sql);

ResultSet rs = prest.executeQuery();

while (rs.next())

{

records = rs.getInt(1);

}

System.out.println("Number of records: " + records);

con.close(); }

catch (SQLException s){ System.out.println("Table does not exist in the database!");

}

}

catch (Exception e){ e.printStackTrace(); }

}

No comments: