1

I am trying to connect to mysql database (as part of the Vertrigo server) on my windows 7 pc, but it keeps throw me the "java.lang.ClassNotFoundException: com.mysql.jdbc.Driver".

Following is my code :

import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.ArrayList;import java.util.LinkedList;import java.util.List;

public class ShippingCompany {

private Connection conn;
private Statement stmt;
private List<Journey> journeyList;
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_URL = "jdbc:mysql://172.16.127.38:3306/testRestricted";

public ShippingCompany(String dbUser, String dbPassword) throws Exception {
    journeyList = new ArrayList<Journey>();
        try {
            Class.forName(DRIVER);
            conn = DriverManager.getConnection(DB_URL, dbUser, dbPassword);
            stmt = conn.createStatement();
        } catch (SQLException e) {
            System.out.println("SQL Exception:" + e);
        }
}

public List<String> readAllPorts() throws SQLException{
     List<String> allPorts = new ArrayList<String>();
        String command = "SELECT * FROM Ports";
        ResultSet rs = stmt.executeQuery(command);
        while (rs.next()) {  // database name string is in first column of result set
            allPorts.add(rs.getString(2));
            //In command concole, print out all ports
            System.out.println(rs.getString(2));
        }
        return allPorts;
}

public List<Journey> getAllJourneys(String startPort, String startDate, String endPort){
    return new LinkedList<Journey>();
}

private void findPaths(Journey journey, String endPort){

}

public void Close(){

}

public static void main(String[] args) throws Exception{
    //TODO : entry point of the program
    ShippingCompany sc = new ShippingCompany("root", "vertrigo");
    sc.readAllPorts();
}

} enter image description here should be

enter image description here

June
  • 974
  • 5
  • 20
  • 34

1 Answers1

1

You need to have mysql connector jar in your classpath while running the program. If you are running it through the command line then you can do something like this:

java -cp  <.;path to sql jar> ShippingCompany
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
  • Thank you, I have tried to add the jar file through the eclipse import function, I have added the jar file into both bin and src, I am still getting this error. Any thoughts? Thanks again. – June Jun 16 '13 at 07:40
  • @Jeffrey From your screenshot, it seems you are trying to import the source but not the library. You need to add the jar like this in eclipse: Project->Properties->Build Path -> Add jar/ Add external jar (depending whether jar is in your project or outside) – Juned Ahsan Jun 16 '13 at 07:42
  • Thanks Juned Ahsan, it works perfectly. – June Jun 16 '13 at 08:06