Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

mysql

jdbc

I tried installing this at home along with Java SDK... The SDK worked fine and I can now use the command prompt to compile java programs into classes...

However I am unsure how to test if JDBC is working to connect to my server/databases/mysql.

As I have a feeling my server (Which is a shared website/webhost) may not allow the connection...

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

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

Thanks alot.

like image 619
James Andrew Avatar asked Nov 18 '10 14:11

James Andrew


People also ask

How do I know if JDBC driver is installed in SQL Server?

The version of the installed Microsoft JDBC Driver for SQL Server can be found in the following ways: Call the SQLServerDatabaseMetaData methods getDriverMajorVersion, getDriverMinorVersion, or getDriverVersion. The version is displayed in the readme. txt file of the product distribution.

How do I know if my JDBC connection is successful?

First, it submits a validation query to the database. Second, it uses the timeout parameter as a threshold for the operation. Finally, the connection is marked as valid if the operation succeeds within the timeout.


2 Answers

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
like image 181
BalusC Avatar answered Sep 20 '22 18:09

BalusC


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.

like image 38
darioo Avatar answered Sep 18 '22 18:09

darioo