Guest User

jdbc1

a guest
Feb 7th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.13 KB | None | 0 0
  1. //STEP 1. Import required packages
  2. import java.sql.*;
  3.  
  4. public class FirstExample {
  5.    // JDBC driver name and database URL
  6.    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
  7.    static final String DB_URL = "jdbc:mysql://localhost/EMP";
  8.  
  9.    //  Database credentials
  10.    static final String USER = "username";
  11.    static final String PASS = "password";
  12.    
  13.    public static void main(String[] args) {
  14.    Connection conn = null;
  15.    Statement stmt = null;
  16.    try{
  17.       //STEP 2: Register JDBC driver
  18.       Class.forName("com.mysql.jdbc.Driver");
  19.  
  20.       //STEP 3: Open a connection
  21.       System.out.println("Connecting to database...");
  22.       conn = DriverManager.getConnection(DB_URL,USER,PASS);
  23.  
  24.       //STEP 4: Execute a query
  25.       System.out.println("Creating statement...");
  26.       stmt = conn.createStatement();
  27.       String sql;
  28.       sql = "SELECT id, first, last, age FROM Employees";
  29.       ResultSet rs = stmt.executeQuery(sql);
  30.  
  31.       //STEP 5: Extract data from result set
  32.       while(rs.next()){
  33.          //Retrieve by column name
  34.          int id  = rs.getInt("id");
  35.          int age = rs.getInt("age");
  36.          String first = rs.getString("first");
  37.          String last = rs.getString("last");
  38.  
  39.          //Display values
  40.          System.out.print("ID: " + id);
  41.          System.out.print(", Age: " + age);
  42.          System.out.print(", First: " + first);
  43.          System.out.println(", Last: " + last);
  44.       }
  45.       //STEP 6: Clean-up environment
  46.       rs.close();
  47.       stmt.close();
  48.       conn.close();
  49.    }catch(SQLException se){
  50.       //Handle errors for JDBC
  51.       se.printStackTrace();
  52.    }catch(Exception e){
  53.       //Handle errors for Class.forName
  54.       e.printStackTrace();
  55.    }finally{
  56.       //finally block used to close resources
  57.       try{
  58.          if(stmt!=null)
  59.             stmt.close();
  60.       }catch(SQLException se2){
  61.       }// nothing we can do
  62.       try{
  63.          if(conn!=null)
  64.             conn.close();
  65.       }catch(SQLException se){
  66.          se.printStackTrace();
  67.       }//end finally try
  68.    }//end try
  69.    System.out.println("Goodbye!");
  70. }//end main
  71. }//end FirstExample
Add Comment
Please, Sign In to add comment