2

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

PVB
  • 103
  • 2
  • 10
  • 1
    Why do you need to change it during code? Why can't you set it as part of the classpath argument when you start your app? – Jeff Storey Jan 03 '12 at 02:18
  • possible duplicate of [How do you change the CLASSPATH within Java?](http://stackoverflow.com/questions/252893/how-do-you-change-the-classpath-within-java) – SimonJ Jan 03 '12 at 02:23
  • im assuming the user will be dumb enough to know what a classpath is!!?? – PVB Jan 03 '12 at 02:23
  • it is not duplicate i think.. i want it for jdbc – PVB Jan 03 '12 at 02:24
  • 1
    Both questions ask how to change the classpath from within Java, and the earlier question has a fairly detailed answer. I don't see how your question being JDBC-oriented changes the validity of that answer? – SimonJ Jan 03 '12 at 02:28

2 Answers2

3

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).

Community
  • 1
  • 1
mgibsonbr
  • 21,755
  • 7
  • 70
  • 112
0

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

James
  • 8,512
  • 1
  • 26
  • 28