If this blog helped you in any way, please donate a dollar here

Wednesday, November 17, 2010

Database connectivity with Java


Spent a lot of time today searching for ways to use Database connectivity on my Ubuntu box. I write the code but it just was not working!


Wrote this code to test for connectivity with this :


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class TestDatabase {


  public static void main(String args[]) {
    Connection con null;
    try {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      con DriverManager.getConnection("jdbc:mysql:///test", "root""root");
      if(!con.isClosed())
        System.out.println("Successfully connected to " +
          "MySQL server using TCP/IP...");
    catch(Exception e) {
      System.err.println("Exception: " e.getMessage());
    finally {
      try {
        if(con != null)
          con.close();
      catch(SQLException e) {}
    }
  }
}




But I could not get it to run!

I kept getting this dreaded error message every time I would run this code :


Exception: com.mysql.jdbc.Driver

Now when I opened up Netbeans and added the library "mysql-connector.jar" to my project, my file would run perfectly! I decided to delve further and tried to explore the main reason why my run failed on the command line.

My compilation command was :

javac TestDatabase.java

My erronous run command was:

java TestDatabase

I googled and manned and finally found the holy grail I was looking for. The problem was in the run command. On changing the run command to :

java -cp .:/usr/share/java/mysql-connector-java.jar TestDatabase

My code finally worked!


NB: The cp switch to the java runtime actually stands for classpath.

1 comment: