Categories: Java

Java Database Connectivity

To connect any Java application to a database using JDBC, follow these five steps. These are the steps to take:

  • Register the Driver class
  • Create connection
  • Create statement
  • Execute queries
  • Close connection
Register the driver class:

The Class class’s forName() method is used to register the driver class. This method is used to load the driver class dynamically.

Syntax:

public static void forName(String className)throws ClassNotFoundException  

For instance:

Class.forName("oracle.jdbc.driver.OracleDriver");  
OR
Class.forName ("com.mysql.jdbc.Driver");
Create a connection object:

The DriverManager class’s getConnection() method is used to connect to the database. This method has several overloaded methods that can be used depending on the situation. To establish a connection, the database name, username, and password are required.

Syntax:

public static Connection getConnection(String url)throws SQLException  

public static Connection getConnection(String url,String name,String password)throws SQLException

Example:

Connection con=DriverManager.getConnection(  
"jdbc:oracle:thin:@localhost:1521:xe","system","password");  

OR

Connection conn = DriverManager.getConnection ("jdbc:mysql://localhost/test", "username", "password");
Create a Statement object:

To create a statement, use the Connection interface’s createStatement() method. The statement’s object is in charge of running queries against the database.

Syntax:

public Statement createStatement()throws SQLException 

For instance:

 stmt = conn.createStatement();
Execute the query:

The executeQuery() method of the Statement interface is used to execute database queries. This method returns a ResultSet object that can be used to retrieve all the records in a table.

Syntax:

public ResultSet executeQuery(String query) throws SQLException

Example:

 stmt = conn.createStatement();
    rs = stmt.executeQuery("SELECT foo FROM bar");
if (stmt.execute("SELECT foo FROM bar")) {
        rs = stmt.getResultSet();
    }
Close the connection object:

By closing the connection object statement, the ResultSet will be automatically closed. The Connection interface’s close() method is used to close the connection.

Syntax:

public void close() throws SQLException

Example:

con.close();  
Simple example with all steps:
import java.sql.*;

public class FirstExample {
   static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
   static final String USER = "guest";
   static final String PASS = "guest123";
   static final String QUERY = "SELECT id, first, last, age FROM Employees";

   public static void main(String[] args) {
      // Open a connection
      try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
         Statement stmt = conn.createStatement();
         ResultSet rs = stmt.executeQuery(QUERY);) {
         // Extract data from result set
         while (rs.next()) {
            // Retrieve by column name
            System.out.print("ID: " + rs.getInt("id"));
            System.out.print(", Age: " + rs.getInt("age"));
            System.out.print(", First: " + rs.getString("first"));
            System.out.println(", Last: " + rs.getString("last"));
         }
      } catch (SQLException e) {
         e.printStackTrace();
      } 
   }
}

Note: also read about the JDBC API(java.sql Package)

Follow Me

If you like my post, please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

What is object oriented design patterns

A design pattern is a reusable solution to a commonly occurring problem in software design. They…

4 months ago

Factory Method Design Pattern in OODP

Factory Method is a creational design pattern that deals with the object creation. It separates…

4 months ago

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

10 months ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

10 months ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

10 months ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

11 months ago