Java JDBC Connection Example Code: Step-by-Step Tutorial

Robert Jul 13, 2026

Java Database Connectivity (JDBC) is a standard API for connectivity between the Java programming language and a wide range of databases. Understanding how to create a JDBC connection is crucial for any Java developer, regardless of the specific database they're working with. Let's dive into a simple yet comprehensive example of a JDBC connection in Java.

Introduction to JDBC | Java Database Connectivity
Introduction to JDBC | Java Database Connectivity

Before we dive into the code, we need to ensure we have the necessary JDBC library for our database. For example, if we're using MySQL, we'd need the MySQL Connector/J library. You can add this library to your project's build path in your Integrated Development Environment (IDE), or include it in your project's classpath.

JDBC Connection Demo
JDBC Connection Demo

Setting Up the JDBC Connection

The first step in connecting to a database using JDBC is to load the driver for that database. This is typically done using the `Class.forName()` method in Java. Here's a basic example:

JDBC Connection
JDBC Connection

```java // Import the necessary classes import java.sql.*; public class JDBCExample { public static void main(String[] args) { try { // Load the JDBC driver Class.forName("com.mysql.cj.jdbc.Driver"); // Now you're ready to connect to the database // ... } catch (ClassNotFoundException e) { e.printStackTrace(); } } } ```

Creating a Connection

Java Switch Example
Java Switch Example

After the driver is loaded, you can create a connection to the database using the `DriverManager.getConnection()` method. Here's how you can do it:

```java String url = "jdbc:mysql://localhost:3306/mydatabase"; String user = "myusername"; String password = "mypassword"; try (Connection connection = DriverManager.getConnection(url, user, password)) { // Use the connection to interact with the database // ... } catch (SQLException e) { e.printStackTrace(); } ```

Executing SQL Statements

JDBC - Java Database Connectivity
JDBC - Java Database Connectivity

With a connection established, you can now execute SQL statements using a `Statement` object. Here's how you can create a `Statement` and use it to execute an SQL statement:

```java try (Connection connection = DriverManager.getConnection(url, user, password); Statement statement = connection.createStatement()) { String sql = "SELECT * FROM mytable"; try (ResultSet resultSet = statement.executeQuery(sql)) { // Process the results of the SQL statement // ... } } catch (SQLException e) { e.printStackTrace(); } ```

Handling Exceptions in JDBC

JDBC ODBC Bridge - Java | Geekboots
JDBC ODBC Bridge - Java | Geekboots

JDBC operations can throw `SQLException` when they encounter an error. It's crucial to handle these exceptions appropriately in your code.

```java try (Connection connection = DriverManager.getConnection(url, user, password)) { String sql = "SELECT * FROM mytable"; try (Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql)) { // Process the results of the SQL statement // ... } catch (SQLException e) { System.err.println("Error executing SQL statement: " + e.getMessage()); } } catch (SQLException e) { System.err.println("Error connecting to the database: " + e.getMessage()); } ```

an image of a computer screen with many lines on the screen and numbers in different colors
an image of a computer screen with many lines on the screen and numbers in different colors
JDBC in Java
JDBC in Java
an image of a computer screen with multiple lines and numbers on it, all in different colors
an image of a computer screen with multiple lines and numbers on it, all in different colors
an image of a computer screen with code numbers on it and the words'datatables'in different languages
an image of a computer screen with code numbers on it and the words'datatables'in different languages
an image of a computer screen with some text on it
an image of a computer screen with some text on it
🔊 Master Java Methods Like a Pro! 🚀
🔊 Master Java Methods Like a Pro! 🚀
Java Cheatsheet
Java Cheatsheet
📘 Must-Know Java Keywords Explained Simply 🔑
📘 Must-Know Java Keywords Explained Simply 🔑
java at a glance 😎
java at a glance 😎
🚀 The Ultimate Guide to Java Method Overloading 🎯
🚀 The Ultimate Guide to Java Method Overloading 🎯
a diagram showing the sequence of data processing
a diagram showing the sequence of data processing
JDBC MySql Bridge - Java | Geekboots
JDBC MySql Bridge - Java | Geekboots
Java Programming CheatsheetIntro to Java Programming: An Interdisciplinary Approach and Computer Science: An Interdisciplinary Approach by Sedgewick and Wayne
Java Programming CheatsheetIntro to Java Programming: An Interdisciplinary Approach and Computer Science: An Interdisciplinary Approach by Sedgewick and Wayne
Free Java Programming Book
Free Java Programming Book
java basics
java basics
Java String Methods
Java String Methods
🔴🔦 Master Java Loops in Minutes! 🚀🔦
🔴🔦 Master Java Loops in Minutes! 🚀🔦
a poster with different types of writing and numbers on it, including the words'jwa beginner notes '
a poster with different types of writing and numbers on it, including the words'jwa beginner notes '
🔥 JAVA LAMBDA EXPRESSIONS SIMPLIFIED! 🚀
🔥 JAVA LAMBDA EXPRESSIONS SIMPLIFIED! 🚀
🚀 MULTITHREADING IN JAVA MADE EASY! ⚡
🚀 MULTITHREADING IN JAVA MADE EASY! ⚡

Remember, in a real-world application, you might want to log these exceptions or throw them up the call stack for further processing, rather than just printing them to the standard error stream.

Using PreparedStatements and Parameterized Queries

In many cases, you'll want to execute SQL statements with placeholders for data values. This is where `PreparedStatement` comes in:

```java String sql = "SELECT * FROM mytable WHERE id = ?"; try (Connection connection = DriverManager.getConnection(url, user, password); PreparedStatement preparedStatement = connection.prepareStatement(sql)) { int idToSearch = 10; preparedStatement.setInt(1, idToSearch); try (ResultSet resultSet = preparedStatement.executeQuery()) { // Process the results of the SQL statement // ... } } catch (SQLException e) { e.printStackTrace(); } ```

Starting from JDBC 4.0, you can use a `try-with-resources` statement to automatically handle the closing of your JDBC resources. This is not only cleaner but also helps prevent resource leaks.

In conclusion, understanding how to create a JDBC connection and interact with a database is a vital skill for any Java developer. By using the examples provided above, you can start building robust and efficient JDBC code for your own projects. Happy coding!