Class.forName(“org.postgresql.Driver”) error

前端 未结 3 918
青春惊慌失措
青春惊慌失措 2021-01-21 22:19

I have simple class. Then I try to compile and run it I see ClassNotFoundException.

import java.sql.*;

public class DBProcessor{

private static String serverAd         


        
相关标签:
3条回答
  • 2021-01-21 22:29

    On the command line, this

    java DBProcessor
    

    should be

    java -cp .;postgresql.jar DBProcessor
    

    And, because it includes java.sql.Driver, when you have it working you could remove

    // try {
    //    Class.forName("org.postgresql.Driver");
    // } catch (ClassNotFoundException e) {
    //    System.err.println("Where is your PostgreSQL JDBC Driver? "
    //            + "Include in your library path!");
    //    e.printStackTrace();
    // }
    

    Per the DriverManager Javadoc,

    The DriverManager methods getConnection and getDrivers have been enhanced to support the Java Standard Edition Service Provider mechanism. JDBC 4.0 Drivers must include the file META-INF/services/java.sql.Driver. This file contains the name of the JDBC drivers implementation of java.sql.Driver. For example, to load the my.sql.Driver class, the META-INF/services/java.sql.Driver file would contain the entry:

     my.sql.Driver
    

    Applications no longer need to explictly load JDBC drivers using Class.forName(). Existing programs which currently load JDBC drivers using Class.forName() will continue to work without modification.

    0 讨论(0)
  • 2021-01-21 22:49

    You need to link the driver to your IDE. if you're using Netbeans, right click on Libraries, Add jar/folder then browse to the driver.

    0 讨论(0)
  • 2021-01-21 22:50

    If the postgresql.jar file is not accessible to the Java runtime environment you will get a 'java.lang.ClassNotFoundException: org.postgresql.Driver' exception.

    The easiest way to make the postgresql jdbc driver accessible to your applications is to install it as a Java Extension. The only thing you need to do is cp, mv or ln the postgresql.jar file into the Java extension directory. There is no need to set CLASSPATH if you do this. The Java extension directory is $JAVA_HOME/jre/lib/ext ($JAVA_HOME on my system is /usr/java/jdk1.3) or for Windows C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext

    This makes life REALLY easy; I didn't have to set CLASSPATH at all in my environment again!

    0 讨论(0)
提交回复
热议问题