Connect Java to a MySQL database
To connect a Java application to a MySQL database, you need to use the JDBC (Java Database Connectivity) API.
To connect a Java application to a MySQL database, you need to use the JDBC (Java Database Connectivity) API.
To start, you need to include the MySQL JDBC driver in your project. Modern Java development typically uses build tools like Maven or Gradle to manage dependencies, but you can also download the driver JAR from the MySQL website and add it to your classpath manually. Note: JDBC 4.0 and later automatically registers the driver, so you do not need to manually load it using Class.forName().
Next, you need to specify the connection URL for the MySQL database. The connection URL has the following format:
jdbc:mysql://<host>:<port>/<database>For example:
jdbc:mysql://localhost:3306/testThis connection URL specifies the mysql protocol, the host name (localhost), the port number (3306), and the database name (test).
To connect to the database, you can use the DriverManager.getConnection() method and pass it the connection URL, the user name, and the password as arguments.
Here is an example of how to connect to a MySQL database in Java:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/test";
String user = "user";
String password = "password";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
// Use the connection here
System.out.println("Connected to the database successfully.");
} catch (SQLException e) {
System.err.println("Failed to connect to the database: " + e.getMessage());
}
}
}