HOWTO · MySQL
How to Connect to a MySQL Database Using JDBC
Build a MySQL JDBC connection URL and use Java with MySQL Connector/J to connect, check the connection, and close resources.
On this page
A MySQL JDBC connection URL has the form jdbc:mysql://host:port/database. In Java, pass that URL, the database username, and the password separately to DriverManager.getConnection. JDBC is the Java API used by an application to work with a database through a driver.
JDBC and MySQL Connection Requirements
You need a Java Development Kit (JDK), a MySQL server that accepts connections from your application, and MySQL Connector/J. Connector/J is the driver that implements JDBC support for MySQL. Add its dependency to your build tool or add the Connector/J JAR to the application’s classpath. The exact dependency version depends on the project and its supported Java and MySQL versions; this example does not assume a particular release.
An IDE can help you write and run Java, but it is optional. Do not copy the driver into a JRE extension directory: configure it as an application dependency so the build and runtime use the same driver. Consult the Connector/J documentation or your build tool’s dependency configuration when selecting and adding the driver.
Build the MySQL JDBC Connection URL
The URL begins with the exact prefix jdbc:mysql://, followed by the MySQL server host, port, and database name. For a local server using the default MySQL port and a database named new, the URL is jdbc:mysql://localhost:3306/new.
Replace localhost with the server name or address when MySQL runs elsewhere. The usual MySQL port is 3306, but use the port configured for your server. Replace new with the database you want to access. The database must exist, and the MySQL account must have permission to connect to it. URL options can be appended after ? when a connection needs additional Connector/J settings; use the options supported by the Connector/J version in your project.
The URL identifies the server and database; it does not contain the account credentials in this example. Keep the username and password separate and provide them as arguments to DriverManager.getConnection. In an application, load credentials from configuration or a secret store rather than committing passwords to source control.
Connect to MySQL with Java
The following complete program reads the URL and credentials from environment variables, loads the supplied driver class name, opens a connection, and runs SELECT 1. Set MYSQL_URL, MYSQL_USER, and MYSQL_PASSWORD before running it. MYSQL_URL should contain the URL for your server and database, such as jdbc:mysql://localhost:3306/new. Add MySQL Connector/J to the runtime classpath and make sure the server is reachable. This service-backed example has not been verified against a configured MySQL instance here, so no connection result is shown.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MySQLJDBC {
public static void main(String[] args) {
String url = System.getenv("MYSQL_URL");
String username = System.getenv("MYSQL_USER");
String password = System.getenv("MYSQL_PASSWORD");
if (url == null || url.isBlank() || username == null || username.isBlank()
|| password == null || password.isBlank()) {
System.out.println("Set MYSQL_URL, MYSQL_USER, and MYSQL_PASSWORD before connecting.");
return;
}
try {
Class.forName("com.mysql.cj.jdbc.Driver");
try (Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery("SELECT 1")) {
if (result.next()) {
System.out.println("Connected; SELECT 1 returned " + result.getInt(1) + ".");
}
}
} catch (ClassNotFoundException | SQLException error) {
System.out.println("Connection failed (" + error.getClass().getSimpleName() + ").");
}
}
}
Class.forName("com.mysql.cj.jdbc.Driver") names the driver class used in this example; make sure the configured Connector/J dependency provides it. DriverManager.getConnection accepts the URL, username, and password as distinct arguments. The try-with-resources statement closes the result set, statement, and connection when execution leaves the block, including when a query reports an error. The message reports only the exception type and omits connection details and credentials.
Verify and Close the Connection
When a connection succeeds, the program reads the first column returned by SELECT 1 and writes a confirmation containing that value. This check shows that the application obtained a connection and executed a query. If the driver cannot load or the server rejects or cannot receive the connection, the program reports the exception type without printing the exception message, which could contain connection details.
Check that the server is running and reachable at the host and port in MYSQL_URL, that the named database exists, and that the account has the required permissions. Also confirm that Connector/J is included on the application’s runtime classpath. A successful connection and query require all three environment variables, a Connector/J dependency, and a reachable MySQL server. When configuration is missing or the driver or connection fails, the program prints a message and returns without setting a nonzero exit status; those paths do not demonstrate a successful query.
To adapt the connection, set the URL and credentials for the target environment, then retain the query or replace it with the database operation your application needs. The URL is the JDBC MySQL connection string, while DriverManager.getConnection combines it with the account credentials to create the connection. The example uses try-with-resources so JDBC resources are closed after the check completes.