Advertisement
Guest User

Untitled

a guest
Nov 1st, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.75 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. /**
  8.  * Simple Java program to connect to MySQL database running on localhost and
  9.  * running SELECT and INSERT query to retrieve and add data.
  10.  * @author Javin Paul
  11.  */
  12. public class JavaToMySQL {
  13.  
  14.     // JDBC URL, username and password of MySQL server
  15.     private static final String url = "jdbc:mysql://localhost:3306/test";
  16.     private static final String user = "root";
  17.     private static final String password = "root";
  18.  
  19.     // JDBC variables for opening and managing connection
  20.     private static Connection con;
  21.     private static Statement stmt;
  22.     private static ResultSet rs;
  23.  
  24.     public static void main(String args[]) {
  25.         String query = "select count(*) from books";
  26.  
  27.         try {
  28.             // opening database connection to MySQL server
  29.             con = DriverManager.getConnection(url, user, password);
  30.  
  31.             // getting Statement object to execute query
  32.             stmt = con.createStatement();
  33.  
  34.             // executing SELECT query
  35.             rs = stmt.executeQuery(query);
  36.  
  37.             while (rs.next()) {
  38.                 int count = rs.getInt(1);
  39.                 System.out.println("Total number of books in the table : " + count);
  40.             }
  41.  
  42.         } catch (SQLException sqlEx) {
  43.             sqlEx.printStackTrace();
  44.         } finally {
  45.             //close connection ,stmt and resultset here
  46.             try { con.close(); } catch(SQLException se) { /*can't do anything */ }
  47.             try { stmt.close(); } catch(SQLException se) { /*can't do anything */ }
  48.             try { rs.close(); } catch(SQLException se) { /*can't do anything */ }
  49.         }
  50.     }
  51.  
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement