daily pastebin goal
56%
SHARE
TWEET

MySQLDB.java

a guest Mar 19th, 2017 90 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package databaseDemo;
  2.  
  3. import java.sql.*; // Step-1
  4.  
  5. public class MySQLDB implements Database {
  6.  
  7.     // Step-2
  8.     // JDBC driver name and database URL
  9.     static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
  10.     static final String DB_URL = "jdbc:mysql://localhost/javaDB";
  11.  
  12.     // Database credentials
  13.     static final String USER = "root";
  14.     static final String PASS = "";
  15.  
  16.     Connection conn = null;
  17.     Statement stmt = null;
  18.    
  19.     @Override
  20.     public void connectDB() throws ClassNotFoundException, SQLException {
  21.         // STEP 3: Register JDBC driver
  22.         Class.forName(JDBC_DRIVER);
  23.  
  24.         // STEP 4: Open a connection
  25.         System.out.println("Connecting to database...");
  26.         conn = DriverManager.getConnection(DB_URL, USER, PASS);
  27.     }
  28.  
  29.     @Override
  30.     public void query(String sql) throws SQLException {
  31.         try {
  32.             connectDB();
  33.         } catch (ClassNotFoundException e) {
  34.             // TODO Auto-generated catch block
  35.             e.printStackTrace();
  36.         }
  37.        
  38.         // STEP 5: Execute a query
  39.         System.out.println("Creating statement...");
  40.         stmt = conn.createStatement();
  41.         ResultSet rs = stmt.executeQuery(sql);
  42.  
  43.         // STEP 6: Extract data from result set
  44.         while (rs.next()) {
  45.             // Retrieve by column name
  46.             int id = rs.getInt("room_id");
  47.             String name = rs.getString("room_name");
  48.  
  49.             // Display values
  50.             System.out.print(" room_id: " + id);
  51.             System.out.println(" room_name: " + name);
  52.  
  53.         }
  54.  
  55.         // STEP 7: Clean-up environment
  56.         rs.close();
  57.         stmt.close();
  58.         conn.close();
  59.     }
  60.  
  61. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top