Advertisement
Guest User

Untitled

a guest
Dec 23rd, 2016
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6.  
  7. public class Main {
  8.  
  9. // JDBC URL, username and password of MySQL server
  10. private static final String url = "jdbc:mysql://localhost:3306/java_connect";
  11. private static final String user = "root";
  12. private static final String password = "";
  13.  
  14. // JDBC variables for opening and managing connection
  15. private static Connection con;
  16. private static Statement stmt;
  17. private static ResultSet rs;
  18.  
  19. public static void main(String args[]) {
  20. String query = "select count(*) from books";
  21.  
  22. try {
  23. // opening database connection to MySQL server
  24. con = DriverManager.getConnection(url, user, password);
  25.  
  26. // getting Statement object to execute query
  27. stmt = con.createStatement();
  28.  
  29. // executing SELECT query
  30. rs = stmt.executeQuery(query);
  31.  
  32. while (rs.next()) {
  33. int count = rs.getInt(1);
  34. System.out.println("Total number of books in the table : " + count);
  35. }
  36.  
  37. } catch (SQLException sqlEx) {
  38. sqlEx.printStackTrace();
  39. } finally {
  40. //close connection ,stmt and resultset here
  41. try { con.close(); } catch(SQLException se) { /*can't do anything */ }
  42. try { stmt.close(); } catch(SQLException se) { /*can't do anything */ }
  43. try { rs.close(); } catch(SQLException se) { /*can't do anything */ }
  44. }
  45. }
  46.  
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement