7

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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
James Andrew
  • 7,197
  • 14
  • 46
  • 62

3 Answers3

15

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

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 1
    As per your deleted *"Which `driverClassName` do I need?"* comment: just pick the one you need for the particular database. For MySQL that's usually `com.mysql.jdbc.Driver`. See also the vendor-specific documentation and the mini tutorial in "See also" section. – BalusC Nov 18 '10 at 14:36
  • Damn, got a fail. :( Time to reinstall :P – James Andrew Nov 18 '10 at 17:36
  • I'd suggest to get through the mini tutorial to ensure that you've covered (and understood) everything :) – BalusC Nov 18 '10 at 17:38
3

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.

darioo
  • 46,442
  • 10
  • 75
  • 103
1

Install a database locally and connect to that.

You can check the connection to the server by using telnet to connect to the port where the database should be listening; if you can open a connection, you know there isn't a network problem (such as a firewall). If JDBC is okay and the network is okay, then you can try connecting to the remote system. If that doesn't work, it's some kind of configuration problem.

Tom Anderson
  • 46,189
  • 17
  • 92
  • 133