To connect to MySQL you need to use the MySQL Connector/J driver. You can download it from http://dev.mysql.com/downloads/connector/j/ or you can use Maven:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
The basic JDBC URL for MySQL is:
jdbc:mysql://<hostname>[:<port>]/<database>[?<propertyName>=<propertyValue>[&<propertyName>=<propertyValue>]...]
Where:
Key | Description | Example |
---|---|---|
<hostname> | Host name of the MySQL server | localhost |
<port> | Port of the MySQL server (optional, default: 3306) | 3306 |
<database> | Name of the database | foobar |
<propertyName> | Name of a connection property | useCompression |
<propertyValue> | Value of a connection property | true |
The supported URL is more complex than shown above, but this suffices for most 'normal' needs.
To connect use:
try (Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost/foobardb", "peter", "nicepassword")) {
// do something with connection
}
For older Java/JDBC versions:
// Load the MySQL Connector/J driver
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost/foobardb", "peter", "nicepassword");
try {
// do something with connection
} finally {
// explicitly close connection
connection.close();
}