DronaBlog

Wednesday, January 4, 2023

How to connect to Database in Java?

 To connect to a database using Java, you will need to use the JDBC (Java Database Connectivity) API. This API provides a standard set of interfaces for connecting to a database, executing queries, and processing the results.





 

Here is an example of Java code that demonstrates how to connect to a database using JDBC:

 

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

 

public class DatabaseConnection {

 

    public static void main(String[] args) {

 

        // Load the JDBC driver

        try {

            Class.forName("com.mysql.jdbc.Driver");

        } catch (ClassNotFoundException e) {

            e.printStackTrace();

            return;

        }

 

        // Establish a connection to the database

        Connection connection = null;

        try {

            connection = DriverManager.getConnection(

                "jdbc:mysql://localhost:3306/mydatabase", "username", "password");

        } catch (SQLException e) {

            e.printStackTrace();

            return;

        }

 

        // Do something with the connection, such as executing a query

        // (omitted for brevity)

 

        // Close the connection

        try {

            connection.close();

        } catch (SQLException e) {

            e.printStackTrace();

        }

    }

}

 

 





In this example, we first load the JDBC driver for MySQL using the Class.forName() method. Then, we use the DriverManager.getConnection() method to establish a connection to the database. Finally, we close the connection using the Connection.close() method.

 

Note that this example uses MySQL as the database, but you can use a different database by simply changing the JDBC driver class and the connection URL. You will also need to provide the appropriate username and password for the database.

No comments:

Post a Comment

Please do not enter any spam link in the comment box.

What is Thread Contention?

  Understanding Thread Contention Thread contention occurs when multiple threads compete for the same resources, leading to conflicts and de...