问题描述
- 创建工具类连接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)
解决方案
运行时报错,可以单步调试一下看看具体是哪一句报错了。
时间: 2024-10-25 17:46:30