Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package databaseDemo;
- import java.sql.*; // Step-1
- public class MySQLDB implements Database {
- // Step-2
- // JDBC driver name and database URL
- static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
- static final String DB_URL = "jdbc:mysql://localhost/javaDB";
- // Database credentials
- static final String USER = "root";
- static final String PASS = "";
- Connection conn = null;
- Statement stmt = null;
- @Override
- public void connectDB() throws ClassNotFoundException, SQLException {
- // STEP 3: Register JDBC driver
- Class.forName(JDBC_DRIVER);
- // STEP 4: Open a connection
- System.out.println("Connecting to database...");
- conn = DriverManager.getConnection(DB_URL, USER, PASS);
- }
- @Override
- public void query(String sql) throws SQLException {
- try {
- connectDB();
- } catch (ClassNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- // STEP 5: Execute a query
- System.out.println("Creating statement...");
- stmt = conn.createStatement();
- ResultSet rs = stmt.executeQuery(sql);
- // STEP 6: Extract data from result set
- while (rs.next()) {
- // Retrieve by column name
- int id = rs.getInt("room_id");
- String name = rs.getString("room_name");
- // Display values
- System.out.print(" room_id: " + id);
- System.out.println(" room_name: " + name);
- }
- // STEP 7: Clean-up environment
- rs.close();
- stmt.close();
- conn.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement