John Eipe
John Eipe

Reputation: 11228

Cannot find the JDBC driver

I have a simple JDBC code.

static Connection c;
static PreparedStatement ps;

public static void initializeDB() throws IOException, ClassNotFoundException, SQLException {
    Properties prop = new Properties();
    prop.load(new FileInputStream("dbconn.properties"));
    String connurl = prop.getProperty("connurl");
    String driver = prop.getProperty("driver");
    String username = prop.getProperty("username");
    String password = prop.getProperty("password");
    System.out.println(driver); //prints "com.mysql.jdbc.Driver"
    Class.forName(driver);
    c = DriverManager.getConnection(connurl, username, password);
  1. But I'm getting

    java.lang.ClassNotFoundException: "com.mysql.jdbc.Driver" at java.net.URLClassLoader$1.run(URLClassLoader.java:202) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:248) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:169) at testapp.DBUpdater.initializeDB(Testapp.java:71) at testapp.Testapp.main(Testapp.java:38)

The property values are perfectly accessed as seen from the print statement. When I replace the variables with the string values directly it works fine!!

  1. When should I use

    prop.load(new FileInputStream(System.getProperty("dbconn.properties")));

  2. When I viewed the Driver class from the mysql-connector jar file, I was expecting to see some static code but didn't find anything.

Upvotes: 0

Views: 2708

Answers (2)

Mark Rotteveel
Mark Rotteveel

Reputation: 109002

It looks like the string has value "com.mysql.jdbc.Driver" (note the double quotes) instead of com.mysql.jdbc.Driver.

Remove those quotes and it should work.

Upvotes: 1

sp00m
sp00m

Reputation: 48817

  1. Try to trim the values of the properties.

  2. I would have load the properties in a static way.

  3. I didn't understand why you had a look within this JAR...

Example:

class Database {

    private final static Properties properties;
    private static Connection c;
    private static PreparedStatement ps;

    static {
        properties = new Properties();
        properties.load(new FileInputStream("dbconn.properties"));
    }

    public static void init() {
        String connurl = properties.getProperty("connurl").trim();
        String driver = properties.getProperty("driver").trim();
        String username = properties.getProperty("username").trim();
        String password = properties.getProperty("password").trim();
        Class.forName(driver);
        c = DriverManager.getConnection(connurl, username, password);
    }

}

Upvotes: 0

Related Questions