Connecting to a Database
To connect to a database in Java, we can use JDBC (Java Database Connectivity). JDBC is a Java API that provides a standard way to interact with relational databases.
Here's how we can establish a connection to a MySQL database using JDBC:
TEXT/X-JAVA
1const connection = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
xxxxxxxxxx
26
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnection {
private static final String DB_URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String USERNAME = "root";
private static final String PASSWORD = "password";
public static Connection getConnection() {
Connection connection = null;
try {
// Register the JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Open a connection
connection = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
System.out.println("Database connected successfully!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment