在Java中连接到oracle DB会返回NullPointerException

时间:2012-01-10 21:35:08

标签: java database oracle

我有这个方法连接到oracle 11g xe。它仍然返回异常java.lang.NullPointerException。我使用Eclipse IDE。请帮助,我不知道如何解决它。

public static Connection connectDB() throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException {

    Connection connection = null;
    try {
        // Load the JDBC driver
        String driverName = "oracle.jdbc.driver.OracleDriver";
        Class.forName(driverName).newInstance();

        // Create a connection to the database
        String serverName = "127.0.0.1";
        String portNumber = "1521";
        String sid = "xe";
        String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
        String username = "peter";
        String password = "pass";
        connection = DriverManager.getConnection(url, username, password);
        System.out.println(connection);
    } catch (ClassNotFoundException e) {
        // Could not find the database driver
    } catch (SQLException e) {
        // Could not connect to the database
    }
    System.out.println(connection);
    return connection;
}

3 个答案:

答案 0 :(得分:2)

问题在于oracle的驱动程序。我通过把我需要把ojdbc14.jar文件放到服务器文件夹中来解决这个问题。我正在使用tomcat,因此我将ojdbc14.jar文件放入文件夹apache-tomcat-7.0.8\lib\

答案 1 :(得分:1)

你忽略了异常,然后希望一切顺利。只是停止忽略异常,你可能会有NPE的根本原因:

public static Connection connectDB() throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException {

    Connection connection = null;
    // Load the JDBC driver
    String driverName = "oracle.jdbc.driver.OracleDriver";
    Class.forName(driverName).newInstance();

    // Create a connection to the database
    String serverName = "127.0.0.1";
    String portNumber = "1521";
    String sid = "xe";
    String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
    String username = "peter";
    String password = "pass";
    connection = DriverManager.getConnection(url, username, password);
    System.out.println(connection);

    System.out.println(connection);
    return connection;
}

答案 2 :(得分:1)

我认为即使发布了堆栈跟踪,问题中发布的代码段中也不会出现NullPointerException。只有两行不是变量初始化或简单System.out.println语句(无论如何都可以处理null)。

Class.forName( driverName ).newInstance();

在找不到Class.forName( driverName )时可能导致异常的行。但是,这会导致出现ClassNotFoundException而不是NullPointerException,因此可以将其删除。

可能导致异常的唯一其他行是

connection = DriverManager.getConnection(url, username, password);

线。但是,urlusernamepassword都是非null,因此此行也不会导致异常。

底线,获取堆栈跟踪,自行分析(使用IDE时只需轻轻一点,只需单击堆栈跟踪并查看IDE将您带到哪里),如果需要,可以使用相关代码在此处发布。

哦,为什么你声明你的方法抛出ClassNotFoundException如果你抓住它并在方法的实现中忽略它。这必须像两个世界中最糟糕的一样