SkolaRajakAndroid

JDBC

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