Advertisement
Guest User

Untitled

a guest
Mar 29th, 2016
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.28 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 = "org.postgresql.Driver";  
  7.    static final String DB_URL = "jdbc:postgresql://localhost/postgres";
  8.  
  9.    //  Database credentials
  10.    static final String USER = "postgres";
  11.    static final String PASS = "";
  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("org.postgresql.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.       String sql2,sql3,sql4;
  29.       sql3="BEGIN WORK";
  30.       sql2="LOCK TABLE public.rawinput";
  31.       sql4="END WORK";
  32.      // /*
  33.       //stmt.executeQuery(sql3);
  34.       //stmt.executeQuery(sql2);
  35.       //stmt.executeQuery(sql4);
  36.        
  37.       sql = "SELECT product_id FROM public.rawinput";
  38.       //ResultSet rs = stmt.executeQuery("");
  39.       ResultSet rs = stmt.executeQuery(sql);
  40.  
  41.       //STEP 5: Extract data from result set
  42.       while(rs.next()){
  43.          //Retrieve by column name
  44.          int id  = rs.getInt("product_id");
  45.        
  46.  
  47.          //Display values
  48.          System.out.println("ID: " + id);
  49.        
  50.       }
  51.      
  52.      
  53.       //extra test
  54.      
  55.      
  56.      
  57.      
  58.      
  59.       //einde extra test
  60.      
  61.       //STEP 6: Clean-up environment
  62.       rs.close();
  63.       stmt.close();
  64.       conn.close();
  65.    }catch(SQLException se){
  66.       //Handle errors for JDBC
  67.       se.printStackTrace();
  68.    }catch(Exception e){
  69.       //Handle errors for Class.forName
  70.       e.printStackTrace();
  71.    }finally{
  72.       //finally block used to close resources
  73.       try{
  74.          if(stmt!=null)
  75.             stmt.close();
  76.       }catch(SQLException se2){
  77.       }// nothing we can do
  78.       try{
  79.          if(conn!=null)
  80.             conn.close();
  81.       }catch(SQLException se){
  82.          se.printStackTrace();
  83.       }//end finally try
  84.    }//end try
  85.    System.out.println("Goodbye!");
  86. }//end main
  87. }//end FirstExample
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement