Java Database Connection Tutorial

In Java, you can connect to a database using the DriverManager.getConnection() method. First, you need to import the java.sql package and then use the following code to connect to the database:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseConnection {
    public static void main(String[] args) {
        Connection connection = null;

        String url = "jdbc:mysql://localhost:3306/mydatabase";
        String username = "username";
        String password = "password";

        try {
            connection = DriverManager.getConnection(url, username, password);
            System.out.println("Database connected!");
        } catch (SQLException e) {
            System.out.println("Failed to connect to database!");
            e.printStackTrace();
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

In the code above, you need to replace url, username, and password with the actual database connection information. Specifically, url is the database connection address, while username and password are the database username and password. Within the try-catch block, call the DriverManager.getConnection() method to connect to the database. If the connection is successful, output “Database connected!”, otherwise output “Failed to connect to database!”. Lastly, in the finally block, close the database connection.

You can use the DriverManager.getConnection() method to connect to the database through the above method.

bannerAds