Java Database Connection Example: Simple Code for Beginners

Robert Jul 13, 2026

Establishing a Java database connection is a crucial task in any Java application involving data management. This process ensures your application can interact with and manipulate data stored in a database. Let's explore how to create a Java database connection, using Java Database Connectivity (JDBC) and MySQL as our example.

JDBC in Java Explained | Database Connectivity Easy Notes
JDBC in Java Explained | Database Connectivity Easy Notes

In this guide, we'll cover the following topics: setting up the JDBC driver, writing a Java code snippet for connecting to a MySQL database, handling database connections, querying data, and writing INSERT and UPDATE operations.

Mastering Java: How to Connect to a Database - Makemychance
Mastering Java: How to Connect to a Database - Makemychance

Setting Up the JDBC Driver

The JDBC driver allows our Java application to connect to the database. For MySQL, we'll use the mysql-connector-java driver. Include this Maven dependency in your Apache Maven project:

JDBC - Java Database Connectivity
JDBC - Java Database Connectivity

```java mysql mysql-connector-java 8.0.26 ```

If you're not using Maven, download the JAR file and add it to your classpath.

Adding the JDBC Driver to the Classpath

JDBC : Java Database Connection Pooling - Playlist
JDBC : Java Database Connection Pooling - Playlist

With Maven, the dependency management takes care of adding the driver to your classpath. If not using Maven, add the JAR file to your project's build path directly.

Alternatively, you can add it manually using the following command:

```bash java -cp path/to/mysql-connector-java-8.0.26.jar java -cp . YourJavaClass ```

Writing the Java Code for Database Connection

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

Now that the driver is set up, let's write a Java program to connect to a MySQL database. We will use a basic try-catch-finally block to ensure our connection is closed properly.

Replace hostname, port, database, username, and password with your actual database credentials:

```java import java.sql.*; public class DatabaseConnection { public static void main(String[] args) { String url = "jdbc:mysql://hostname:port/database"; String user = "username"; String password = "password"; try (Connection conn = DriverManager.getConnection(url, user, password)) { if (conn != null) { System.out.println("Connected to the database!"); } } catch (SQLException e) { System.out.println("Error connecting to the database:"); e.printStackTrace(); } } } ```

Handling Database Connections

How to setup JNDI Database Connection pool in Tomcat - Spring Tutorial Example
How to setup JNDI Database Connection pool in Tomcat - Spring Tutorial Example

Always close your database connections when you're done using them. Using try-with-resources (as shown above) automatically closes the connection once the block of code is executed.

For long-running applications, consider using a connection pool to manage your database connections more efficiently.

Java Database Connection Pooling: BoneCP vs DBPool vs C3PO - Which is Best?
Java Database Connection Pooling: BoneCP vs DBPool vs C3PO - Which is Best?
a diagram with two different types of data and one type of information on it, including the
a diagram with two different types of data and one type of information on it, including the
How to Connect Java Programs and Databases
How to Connect Java Programs and Databases
JDBC ODBC Bridge - Java | Geekboots
JDBC ODBC Bridge - Java | Geekboots
JDBC Connection
JDBC Connection
a diagram showing the sequence of data processing
a diagram showing the sequence of data processing
How to Develop a Role-based Login Application in Java?-Krazytech
How to Develop a Role-based Login Application in Java?-Krazytech
Database Connection Pool
Database Connection Pool
JDBC MySql Bridge - Java | Geekboots
JDBC MySql Bridge - Java | Geekboots
JDBC Connection Demo
JDBC Connection Demo
Free Java Programming Book
Free Java Programming Book
Oracle Database Connection in Java
Oracle Database Connection in Java
Java Cheatsheet
Java Cheatsheet
Learn Java Collections Fast 🚀 | ArrayList HashMap Set Queue Explained
Learn Java Collections Fast 🚀 | ArrayList HashMap Set Queue Explained
JDBC Tutorial: Connecting Java to Databases Like a Pro
JDBC Tutorial: Connecting Java to Databases Like a Pro
a diagram showing the different types of web servers
a diagram showing the different types of web servers
Java Collection Framework: ArrayList Explained Visually
Java Collection Framework: ArrayList Explained Visually
JDBC in Java
JDBC in Java
JDBC in Java
JDBC in Java
Database connectiom
Database connectiom

Querying Data

Let's retrieve data from our database. Here's an example of fetching and printing all records from a table named users:

```java try (Connection conn = DriverManager.getConnection(url, user, password); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM users")) { while (rs.next()) { System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name")); } } ```

You can modify the SELECT query to fit your specific needs.

INSERT and UPDATE Operations

To insert or update data, use the PreparedStatement class, which provides methods for executing SQL statements and handling parameter inputs:

```java String sqlInsert = "INSERT INTO users (id, name) VALUES (?, ?)"; String sqlUpdate = "UPDATE users SET name = ? WHERE id = ?"; try (Connection conn = DriverManager.getConnection(url, user, password); PreparedStatement pstmt = conn.prepareStatement(sqlInsert)) { pstmt.setInt(1, 1); // Set the first parameter (id) pstmt.setString(2, "John Doe"); // Set the second parameter (name) int rowsAffected = pstmt.executeUpdate(); System.out.println("Rows inserted: " + rowsAffected); } // Update operation follows a similar pattern ```

This covers the basic creation of a Java database connection and some common database operations. To learn more, explore the official JDBC documentation and consider using higher-level libraries, such as Hibernate or Spring Data JPA.

Happy coding, and remember to always test your code thoroughly and follow best security practices for handling database credentials!