Connecting to a database with JDBC is easy but gets a little more complicated if a secure connection is needed. This is how a secure connection to MySQL is established using keystore/truststore SSL keys. Overall, nothing too spectacular here but a useful reference.
Java
The Java code to get a secure JDBC connection to MySQL is easy. It is a matter of adding properties to the URL connection string which inform the MySQL JDBC driver to use a secure connection.
String username = "[USERNAME]";
String password = "[PASSWORD]";
StringBuilder url = new StringBuilder();
url.append("jdbc:mysql://[SERVER]/[SCHEMA]?")
.append("useSSL=true&")
.append("requireSSL=true&")
;
Connection conn = DriverManager.getConnection(url.toString(), username, password);
System Properties
The properties on the URL connection string tell the MySQL JDBC driver to use a secure connection but you still need to tell your application where the keystore/truststore SSL keys are located. Do this using the following system properties when you start the JVM.
-Djavax.net.ssl.trustStore=C:\temp\cacerts.jks
-Djavax.net.ssl.trustStorePassword=[PASSWORD]
-Djavax.net.ssl.keyStore=C:\temp\keystore.jks
-Djavax.net.ssl.keyStorePassword=[PASSWORD]
These files will of course need the the keys off your MySQL server.