JDBC in Java: A Complete Guide to Database Connectivity with Examples

Harshal Deshmukh
4 min readApr 4, 2023

--

Introduction to JDBC:

Java Database Connectivity, or JDBC in short, is a Java-based application programming interface (API) that allows developers to interact with relational databases using the Java programming language. JDBC is an essential tool for any Java developer who needs to work with databases, and it is a key component in building robust and scalable database-driven applications.

JDBC provides a standard way to interact with different types of databases, including MySQL, Oracle, Microsoft SQL Server, and many others. This allows developers to write database code once and run it on any platform that supports JDBC.

Connecting to a Database:

The first step in using JDBC is to establish a connection to the database. To do this, we need to provide a JDBC driver that corresponds to the database we are using. The JDBC driver is responsible for communicating with the database and translating Java code into SQL statements that the database can understand.

Once we have the JDBC driver, we can use it to create a connection object that represents a connection to the database. Here’s an example of how to create a JDBC connection:

import java.sql.*;

public class JdbcExample {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydatabase", "username", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM customers");
while (rs.next())
System.out.println(rs.getInt(1) + " " + rs.getString(2));
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

In this example, we are connecting to a MySQL database using the com.mysql.jdbc.Driver JDBC driver. We then create a connection object using the DriverManager.getConnection() method and passing in the database URL, username, and password. We also create a statement object using the connection.createStatement() method, which we use to execute an SQL query that selects all the rows from the customers table. Finally, we close the connection using the connection.close() method.

Executing SQL Statements:

Once we have established a connection to the database, we can use JDBC to execute SQL statements and retrieve data from the database. JDBC supports three types of SQL statements:

  1. DDL (Data Definition Language) statements: used to create, modify, and delete database objects such as tables, views, and indexes.
  2. DML (Data Manipulation Language) statements: used to manipulate data within tables, such as insert, update, and delete operations.
  3. DQL (Data Query Language) statements: used to retrieve data from tables, such as select operations.

Here’s an example of how to execute a simple SQL query using JDBC:

Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM customers");
while (rs.next())
System.out.println(rs.getInt(1) + " " + rs.getString(2));

In this example, we create a statement object using the connection.createStatement() method, and then execute an SQL query that selects all the rows from the customers table. We then iterate over the results using the ResultSet object and print out the values of the first and second columns for each row.

Handling Transactions:

JDBC also provides support for database transactions, which are a way to group a set of SQL statements into a single unit of work that must either be completed in its entirety or rolled back if any part of it fails.

To use transactions in JDBC, we need to set the auto-commit property of the connection object to false, which tells JDBC to group all the SQL statements into a single transaction. We can then use the commit() method to commit the transaction if all the statements complete successfully, or the rollback() method to roll back the transaction if any statement fails.

Here’s an example of how to use transactions in JDBC:

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
try {
con.setAutoCommit(false);
Statement stmt = con.createStatement();
stmt.executeUpdate("UPDATE customers SET balance = balance - 100 WHERE id = 1");
stmt.executeUpdate("UPDATE customers SET balance = balance + 100 WHERE id = 2");
con.commit();
} catch (Exception e) {
con.rollback();
System.out.println("Transaction rolled back: " + e.getMessage());
} finally {
con.setAutoCommit(true);
con.close();
}

In this example, we start by setting the auto-commit property of the connection object to false. We then create a statement object and execute two SQL statements that update the balances of two customers. If both statements complete successfully, we call the commit() method to commit the transaction. If any statement fails, we catch the exception, call the rollback() method to roll back the transaction, and print out an error message. Finally, we set the auto-commit property back to true and close the connection.

Handling Exceptions:

JDBC can throw a variety of exceptions, including SQLException, which is the base class for all JDBC exceptions. It is important to handle exceptions properly in JDBC to ensure that the application handles errors gracefully and does not leave database connections open.

Here’s an example of how to handle exceptions in JDBC:

try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM customers");
while (rs.next())
System.out.println(rs.getInt(1) + " " + rs.getString(2));
con.close();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}

In this example, we create a connection object, a statement object, and a result set object. We then iterate over the result set and print out the values of the first and second columns for each row. If any SQLException occurs, we catch it and print out the error message, SQL state, and vendor-specific error code.

Conclusion

JDBC is an essential tool for any Java developer who needs to work with databases. It provides a standard way to interact with different types of databases, and allows developers to write database code once and run it on any platform that supports JDBC. In this blog post, we covered the basics of JDBC, including connecting to a database, executing SQL statements, handling transactions, and handling exceptions. By mastering these concepts, you’ll be well on your way to building robust and scalable database-driven applications using Java.

--

--