---
title: "How to connect Java to a Database?"  
description: "How to connect Java to a Database?"  
author: "Revati S Misra"  
published: 2023-08-21  
updated: 2023-08-23  
canonical: https://www.mindstick.com/forum/159618/how-to-connect-java-to-a-database  
category: "java"  
tags: ["database", "java", "database connection"]  
reading_time: 2 minutes  

---

# How to connect Java to a Database?

How to [connect](https://www.mindstick.com/articles/12810/how-to-connect-tablet-to-external-monitor-or-flat-screen-tv-using-computer-adapters) [Java](https://www.mindstick.com/articles/12214/web-development-company-in-india-laid-on-the-foundation-of-concrete-java-programming) to a [Database](https://www.mindstick.com/articles/12226/use-of-database-in-sencha-extjs-and-insert-record-from-user-form-using-ajax)?

## Replies

### Reply by Aryan Kumar

To connect Java to a database, you can use the JDBC (Java Database Connectivity) API. The JDBC API provides a standard way for Java programs to connect to and interact with databases.

To connect Java to a database, you need to:

1. Install the JDBC driver for the database you want to connect to.
2. Create a connection object.
3. Create a statement object.
4. Execute a query or update statement.
5. Process the results of the query or update statement.
6. Close the connection object.

Here is an example of how to connect Java to a MySQL database:

```plaintext
import java.sql.*;

public class JDBCExample {

    public static void main(String[] args) throws SQLException {
        // Load the MySQL JDBC driver.
        Class.forName("com.mysql.jdbc.Driver");

        // Create a connection to the database.
        String url = "jdbc:mysql://localhost:3306/mydatabase";
        String username = "root";
        String password = "password";
        Connection connection = DriverManager.getConnection(url, username, password);

        // Create a statement object.
        Statement statement = connection.createStatement();

        // Execute a query.
        String query = "SELECT * FROM users";
        ResultSet resultSet = statement.executeQuery(query);

        // Process the results of the query.
        while (resultSet.next()) {
            System.out.println(resultSet.getString("username"));
        }

        // Close the connection object.
        connection.close();
    }
}
```

In this example, we first load the MySQL JDBC driver. Then, we create a connection to the database using the `DriverManager.getConnection()` method. Next, we create a statement object. Then, we execute a query using the `statement.executeQuery()` method. Finally, we close the connection object.


---

Original Source: https://www.mindstick.com/forum/159618/how-to-connect-java-to-a-database

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
