PVB
PVB

Reputation: 103

trying to change classpath through code?

i want to connect to a postgresql database using the jdbc4 driver, but would like to set the classpath during the running of the program. The purpose is to register the driver for database connectivity. The following code explains what i intend to do, but alas the code doesn't work ("Couldn't find driver!"). why can't i connect this way? could i follow another way across for achieving the same?

    String originalclasspath = System.getProperty("java.class.path");

    System.setProperty("java.class.path",originalclasspath + ";E:\\postgresql-9.0-802.jdbc4.jar");

    System.out.println(System.getProperty("java.class.path"));

    System.out.println("Checking if Driver is registered with DriverManager.");
    try {
        Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException cnfe) {
        System.out.println("Couldn't find the driver!");
        cnfe.printStackTrace();
        System.exit(1);
    }

please reply thanks in advance

Upvotes: 2

Views: 3137

Answers (2)

mgibsonbr
mgibsonbr

Reputation: 22007

According to this answer, there's no way to change the system classpath reliably. This other question suggests a way of loading JDBC drivers via classloaders (Direct link: http://www.kfu.com/~nsayer/Java/dyn-jdbc.html).

Upvotes: 3

James
James

Reputation: 8586

I'm not aware of a way to change the classpath for the default classloader, after your program starts. If you absolutely cannot set the classpath prior to running, however, you could try to the load the class via a custom ClassLoader, via something like the following:

http://java.sun.com/developer/onlineTraining/Security/Fundamentals/magercises/ClassLoader/FileClassLoader.java

Upvotes: 0

Related Questions