2 arnoldstephen ArnoldStephen 于 2016.01.13 21:51 提问

创建工具类连接Oracle数据库时报错

属性文件:db.properties
jdbc.driver = oracle.jdbc.OracleDriver
jdbc.url = jdbc:oracle:thin:@localhost:1521:orcl
jdbc.user = c##saturn
jdbc.password = saturn

连接数据库的工具类:DBUtility.java
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class DBUtility {
private static Properties properties = new Properties();
private static String driver = null;
private static String url = null;
private static String user = null;
private static String password = null;

static {
    try {
        properties.load(DBUtility.class.getClassLoader().getResourceAsStream("TestDBUtility/properties/db.properties"));
        driver = properties.getProperty("jdbc.driver");
        url = properties.getProperty("jdbc.url");
        user = properties.getProperty("jdbc.user");
        password = properties.getProperty("jdbc.password");

        Class.forName(driver);

    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

public static Connection openConnection() throws SQLException {

    return DriverManager.getConnection(url, user, password);
}

public static void closeConnection(Connection con) {
    try {
        if(con != null) {
            con.close();
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

}

EmpDAO.java

import java.sql.*;

public class EmpDAO {

public static void main(String[] args) {

    new EmpDAO().findAll();
}

public void findAll() {

    Connection con = null;
    Statement stat = null;
    ResultSet rs = null;

    try {
        con = DBUtility.openConnection();
        stat = con.createStatement();
        rs = stat.executeQuery("SELECT empno, ename, sal, hiredate FROM emp");

        while(rs.next()) {
            System.out.println(rs.getInt("empno") + "," + rs.getString("ename") + "," + rs.getDouble("sal") + "," + rs.getDate("hiredate"));
        }

    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if(rs != null) {
                rs.close();
            }
            if(stat != null) {
                stat.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        DBUtility.closeConnection(con);
    }
}

}

运行时报错:
Exception in thread "main" java.lang.NoClassDefFoundError: Could not initialize class DBUtility
at EmpDAO.findAll(EmpDAO.java:39)
at EmpDAO.main(EmpDAO.java:7)

1个回答

91program
91program   Ds   Rxr 2016.01.13 22:32

运行时报错,可以单步调试一下看看具体是哪一句报错了。

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!