JDBC Select Database



In this example, we are looking into the selection of JDBC database tutorial. We are going to select the Database “student” using Java.

JDBC Select Database :

package com.c4learn.jdbc;

import java.sql.*;

public class JDBCSelectDB {
  // JDBC driver name and database URL
  static final 
        String DB_URL = "jdbc:mysql://localhost/student";

  // 1. Database User name & Password
  static final String USER = "admin";
  static final String PWD = "password";

  public static void main(String[] args) {
    Connection con = null;
    Statement statement = null;
    try {
      // 2. Register JDBC driver
      Class.forName("com.mysql.jdbc.Driver");

      // 3. Open a connection
      System.out.println("Connecting to database...");
      con = DriverManager.getConnection(DB_URL, USER,PWD);

      System.out.println("Database Connected...");

    } catch (SQLException e) {
      System.out.println(e.getMessage());
    } catch (Exception e) {
      System.out.println(e.getMessage());
    } finally {
      try {
        if (statement != null)
          statement.close();
      } catch (SQLException e) {
      }
      try {
        if (con != null)
          con.close();
      } catch (SQLException se) {
        System.out.println(se.getMessage());
      }
    }
  }
}

Output :

Connecting to database...
Database selected successfully...

Explanation : JDBC Select Database

In any DB application first step is to create the Database Schema. In this case we have used the MySQL database to create the schema. In order to achieve this we need to carry out following steps.

Step 1 : Importing the packages :

When we are dealing with the database connectivity then we need to include the required jar file which is necessary for the database programming.

import java.sql.*;

Step 2 : Registering JDBC driver :

After importing the packages we need to initialize a driver to open a communications channel with the database.

Class.forName("com.mysql.jdbc.Driver");

Step 3 : Open a connection .

DriverManager.getConnection() method is required to create a Connection object.
It represents a physical connection with database server. We have created the DB url like this –

String DB_URL = "jdbc:mysql://localhost/student";

Now we need to connect database using the following statements.

System.out.println("Connecting to database...");
con = DriverManager.getConnection(DB_URL, USER,PWD);

Using the statement object we can create a query and submit it to the database.

Step 4 : Clean up the environment .

After the execution of the query we need to clean up the resources. It requires explicitly closing all database resources

if (statement != null)
       statement.close();

and

if (con != null)
          con.close();