Advertisement
Guest User

Untitled

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