JDBC 2: Database Class

The following is the class I’m going to use for the main part of this tutorial. It’s just the Quick Start code broken down into methods.

Update: Follow this link to watch a YouTube demonstration of this lesson

package dbase2016;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author ajb
 */
public class DBase {

    private static Connection con;

    DBase() {
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
        } catch (Exception ex) {
            System.err.println(ex);
        }

    }

    public static void makeConnection() {
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bluecoat", "root", "");
        } catch (SQLException ex) {
            System.err.println(ex);
        }

    }


}

Check the connection by calling the makeConnection() method as follows. If everything is okay the program will simply terminate. If an exception is thrown, check your port number, username and password.


package dbase2016;

/**
 *
 * @author ajb
 */
public class DBase2016 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
    DBase.makeConnection();
    }

}

Leave a Comment