Java JDBC: Core Components

In this article, we will learn some of the core components of JDBC

 

JDBC Core components

  • DriverManager
  • Driver
  • Connection
  • Statement
  • ResultSet

 

1. DriverManager

  • DriverManager is a mean through which it connects to databases using appropriate driver supplied from Java application
  • DriverManager registers all driver requests comes from Java application and picks up appropriate driver to connect to database
    public static void registerDriver(Driver driver);
    
  • DriverManager has number of useful static methods to get connection objects, these are
    public static Connection getConnection(String dbUrl);
    
    public static Connection getConnection(String dbUrl, 
    		String username,String password);
    
    public static Connection getConnection(String dbUrl, 
    		Properties props);
    

 

2. JDBC Driver

  • Drivers are the one which actually communicates with the databases
  • But user generally never interact with drivers directly
  • Instead, user go through DriverManager to register and de-register drivers and then communicate with database

 

3. Connection

  • After registering drivers, DriverManager has got number of static getConnection() method to return Connection object
  • It is only after successfully getting connection object, user can interact with database
  • Connection interface also got some useful methods like setAutoCommit(boolean), commit(), rollback() methods to handle transaction
  • Using connection object, we can create/prepare all three types of statements i.e.;
    createStatement(); // for Statement
    prepareStatement(); // for PreparedStatement
    prepareCall(); // for CallableStatement
    

 

4. Statement

  • Statement interface is the one which is actually used to execute queries like inserting new record or updating an existing record
  • executeQuery(String sqlQuery); and executeUpdate(String sqlQuery) are the most commonly used methods from Statement interface
  • executeQuery(String sqlQuery); returns object of ResultSet
  • There is also executeBatch(); method for batch execution

 

5. ResultSet

  • ResultSet holds data retrieved from database when performing/executing queries (both SQL and MySQL)
  • You can traverse in ResultSet to read data one-by-one, but in forward direction only
  • But by setting static variable “TYPE_SCROLL_INSENSITIVE” in createStatement(), we can make it scrollable in both directions
  • Similarly, by setting static variable “CONCUR_UPDATABLE” in createStatement(), we can make ResultSet updatable, as it is not updatable by default

 

Read Also:

 

References:

 

Happy Coding !!
Happy Learning !!

Java JDBC: Connection Steps
Java JDBC: List of Drivers and URL for all databases