How to test if JDBC driver is installed correctly and if the DB can be connected?

How can I test that the JDBC was installed correctly without having to connect to a server?

Just check if Class#forName() on the JDBC driver doesn't throw ClassNotFoundException.

try {
    Class.forName(driverClassName);
    // Success.
}
catch (ClassNotFoundException e) {
    // Fail.
}

And then how can I test (Seperate code please) that the (now confirmed working) JDBC is connecting to my databases?

Just check if DriverManager#getConnection() or DataSource#getConnection() doesn't throw SQLException.

try (Connection connection = DriverManager.getConnection(url, username, password)) {
    // Success.
}
catch (SQLException e) {
    // Fail.
}

See also

  • Exceptions tutorial
  • JDBC+MySQL mini tutorial

First, download MySQL's JDBC driver and put it somewhere in your application's classpath.

Second, try to register that driver in your Java code, using

Class.forName("com.mysql.jdbc.Driver");

If that doesn't throw an exception, you've managed to register sucessfully.

Third, check if your connection works:

Connection conn =  DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","user", "pass");

Substitute your URL, username and password as needed.

Tags:

Mysql

Java

Jdbc