JDBC

Basic Use Cases

What is JDBC

Why use JDBC

JDBC Statement Classes

Procedure to Connect to Database with JDBC

  1. Add a connector dependency
  2. Register Database Driver
  3. Initialize Connection by providing each of the following to DriverManager:
    • Database URL
    • Username
    • Password
  4. Prepare a statement
  5. Execute the statement
  6. Retrieve Database results

JDBC Procedure to Connect to Database

Step 0 - Add connector dependency
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.18</version>
</dependency>

JDBC Procedure to Connect to Database

Step 1 - Register Driver

JDBC Procedure to Connect to Database

Step 1 - Register Driver

static void registerJDBCDriver() {
    // Attempt to register JDBC Driver
    try {
        DriverManager.registerDriver(Driver.class.newInstance());
    } catch (InstantiationException | IllegalAccessException | SQLException e1) {
        throw new SQLError(e1);
    }
}

public static void main(String[] args) {
    registerJDBCDriver();
}

JDBC Procedure to Connect to Database

Step 2 - Initialize Connection
static Connection getConnection(String dbVendor) {
    String username = "root";
    String password = "";
    String url = "jdbc:" + dbVendor + "://127.0.0.1/";
    try {
        return DriverManager.getConnection(url, username, password);
    } catch (SQLException e) {
        throw new Error(e);
    }
}

public static void main(String[] args) {
    registerJDBCDriver();
    Connection mysqlConnection = getConnection("mysql");
    Connection mariadbConnection = getConnection("mariadb");
}

JDBC Procedure to Connect to Database

Step 3 - Create Statement
static Statement getScrollableStatement(Connection connection) {
    int resultSetType =  ResultSet.TYPE_SCROLL_INSENSITIVE;
    int resultSetConcurrency = ResultSet.CONCUR_READ_ONLY;
    try { // scrollable statements can be iterated more than once without closing
        return connection.createStatement(resultSetType, resultSetConcurrency);
    } catch (SQLException e) {
        throw new Error(e);
    }
}

public static void main(String[] args) {
    registerJDBCDriver();
    Connection mysqlDbConnection = getConnection("mysql");
    Statement scrollableStatement = getScrollableStatement(mysqlDbConnection);
}

JDBC Procedure to Connect to Database

Step 4A - Executing Statement; creating Database
static void executeStatement(Connection connection, String sqlStatement) {
    try {
        Statement statement = getScrollableStatement(connection);
        statement.execute(sqlStatement);
        connection.commit();
    } catch (SQLException e) {
        throw new Error(e);
    }
}

public static void main(String[] args) {
    registerJDBCDriver();
    Connection mysqlDbConnection = getConnection("mysql");
    executeStatement(mysqlDbConnection, "CREATE DATABASE IF NOT EXISTS databaseName;");
    executeStatement(mysqlDbConnection, "USE databaseName;");
}

JDBC Procedure to Connect to Database

Step 4B - Executing Statement; creating Table
public static void main(String[] args) {
  registerJDBCDriver();
  Connection mysqlDbConnection = getConnection("mysql");
  executeStatement(mysqlDbConnection, "CREATE DATABASE IF NOT EXISTS databaseName;");
  executeStatement(mysqlDbConnection, "USE databaseName;");
  executeStatement(mysqlDbConnection, new StringBuilder()
      .append("CREATE TABLE IF NOT EXISTS databaseName.pokemonTable(")
      .append("id int auto_increment primary key,")
      .append("name text not null,")
      .append("primary_type int not null,")
      .append("secondary_type int null);")
      .toString());
}

JDBC Procedure to Connect to Database

Step 4C - Executing Statement; populating Table
public static void main(String[] args) {
  registerJDBCDriver();
  Connection mysqlDbConnection = getConnection("mysql");

  executeStatement(mysqlDbConnection, "CREATE DATABASE IF NOT EXISTS databaseName;");
  executeStatement(mysqlDbConnection, "USE databaseName;");
  executeStatement(mysqlDbConnection, new StringBuilder()
      .append("CREATE TABLE IF NOT EXISTS databaseName.pokemonTable(")
      .append("id int auto_increment primary key,")
      .append("name text not null,")
      .append("primary_type int not null,")
      .append("secondary_type int null);")
      .toString());
  
  executeStatement(mysqlDbConnection, new StringBuilder()
      .append("INSERT INTO databaseName.pokemonTable(")
      .append("id, name, primary_type, secondary_type) ")
      .append("VALUES (12, 'Ivysaur', 3, 7);")
      .toString());
}

JDBC Procedure to Connect to Database

Step 5A - Defining Query Execution & Result Printing
static ResultSet executeQuery(Connection connection, String sqlQuery) {
    try {
        Statement statement = getScrollableStatement(connection);
        return statement.executeQuery(sqlQuery);
    } catch (SQLException e) {
        throw new Error(e);
    }
}

static void printResults(ResultSet resultSet) {
    try {
        for (Integer rowNumber = 0; resultSet.next(); rowNumber++) {
            String firstColumnData = resultSet.getString(1);
            String secondColumnData = resultSet.getString(2);
            String thirdColumnData = resultSet.getString(3);
            System.out.println(new StringJoiner("\n")
                    .add("Row number = " + rowNumber.toString())
                    .add("First Column = " + firstColumnData)
                    .add("Second Column = " + secondColumnData)
                    .add("Third column = " + thirdColumnData)
                    .toString());
        }
    } catch (SQLException e) {
        throw new Error(e);
    }
}

JDBC Procedure to Connect to Database

Step 5B - Executing Query; Retrieving Results
public static void main(String[] args) {
  registerJDBCDriver();
  Connection mysqlDbConnection = getConnection("mysql");

  executeStatement(mysqlDbConnection, "DROP DATABASE IF EXISTS databaseName;");
  executeStatement(mysqlDbConnection, "CREATE DATABASE IF NOT EXISTS databaseName;");
  executeStatement(mysqlDbConnection, "USE databaseName;");
  executeStatement(mysqlDbConnection, new StringBuilder()
      .append("CREATE TABLE IF NOT EXISTS databaseName.pokemonTable(")
      .append("id int auto_increment primary key,")
      .append("name text not null,")
      .append("primary_type int not null,")
      .append("secondary_type int null);").toString());

  executeStatement(mysqlDbConnection, new StringBuilder()
      .append("INSERT INTO databaseName.pokemonTable(")
      .append("id, name, primary_type, secondary_type) ")
      .append("VALUES (12, 'Ivysaur', 3, 7);").toString());

  String query = "SELECT * FROM databaseName.pokemonTable;";
  ResultSet resultSet = executeQuery(mysqlDbConnection, query);
  printResults(resultSet);
}

JDBC Procedure to Connect to Database

Step 5C - Viewing Retrieved Results
Row number = 0
First Column = 12
Second Column = Ivysaur
Third column = 3