Sobes.tech
Junior

How to connect to a database?

sobes.tech AI

Answer from AI

To establish a connection with a database in Java, the JDBC API is used.

Main steps:

  1. Load the database driver.
  2. Establish a connection to the database.
// 1. Loading the driver
try {
    Class.forName("com.mysql.cj.jdbc.Driver"); // Example for MySQL
    // Class.forName("org.postgresql.Driver"); // Example for PostgreSQL
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}

// 2. Establishing the connection
String url = "jdbc:mysql://localhost:3306/mydatabase"; // Database URL
String user = "root"; // Username
String password = "password"; // Password

Connection connection = null;
try {
    connection = DriverManager.getConnection(url, user, password);
    if (connection != null) {
        System.out.println("Database connection established!");
    }
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    // Closing the connection (important!)
    if (connection != null) {
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Alternative approach using DataSource (for connection pools):

import javax.sql.DataSource;
import com.mysql.cj.jdbc.MysqlDataSource; // Example for MySQL

// ...

DataSource dataSource = new MysqlDataSource();
// Configure dataSource (URL, user, password, etc.)
// ((MysqlDataSource) dataSource).setURL("jdbc:mysql://localhost:3306/mydatabase");
// ((MysqlDataSource) dataSource).setUser("root");
// ((MysqlDataSource) dataSource).setPassword("password");

Connection connection = null;
try {
    connection = dataSource.getConnection();
    if (connection != null) {
        System.out.println("Connection obtained from pool!");
    }
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    // Closing the connection (returns to pool)
    if (connection != null) {
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Using DataSource is preferable in real applications, especially in multithreaded environments, as it allows the use of connection pools.

How to connect to a database? — Java - sobes.tech