楼主在学JDBC,Src下建立的properties文件
这加载代码
prop.load(new FileReader(JDBCUtils.class.getClassLoader().getResource("config.properties").getPath()));
正确吗
试试这样行不 prop.load(JDBCUtils.class.getClass().getClassLoader().getResourceAsStream("config.properties"))
这样行不行 prop.load(JDBCUtils.class.getClass().getClassLoader().getResourceAsStream("config.properties"))
检查下config.properties是不是在src路径下
用的是IDEA 还是eclipse
把你的包结构粘贴出来看一下,getResourceAsStream()这个方法是获取配置文件夹路径下的配置文件,所以有可能是你的文件没放对位置
不是很清楚你的代码结构,你是用sql server吗?
我提供一下以前的笔记吧:
private Object targer;
public JDBCUtilHandler(Object targer) {
this.targer = targer;
}
// private的作用:不要影响使用者的视线
// 第一步:获取数据连接,让appliction server能够与db server进行交互
private String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private String url = "jdbc:sqlserver://localhost:1434;DatabaseName=CardDB";
private String name = "sa";
private String pwd = "";
private Connection conn = null;
private Statement stmt = null;
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object returnValue = null;
before();
try {
returnValue = method.invoke(targer, args);
} catch (Exception e) {
System.out.println("执行核心业务逻辑的SQL语句时有异常:" + e.getMessage());
}
after();
return returnValue;
}
private void before() {
// 第一,加载驱动
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
// 第2,获取连接
try {
conn = DriverManager.getConnection(url, name, pwd);
} catch (Exception e) {
System.out.println("获取数据库连接时有异常:" + e.getMessage());
}
// 第3,创建statement
try {
stmt = conn.createStatement();
} catch (SQLException e) {
System.out.println("创建Statement有异常:" + e.getMessage());
}
// ((JDBCUtilImpl)targer).setStmt(stmt);
Method myMethod_setStmt;
try {
myMethod_setStmt = targer.getClass().getMethod("setStmt", Statement.class);
myMethod_setStmt.invoke(targer, stmt);
} catch (Exception e) {
System.out.println("注入stmt时发生异常:" + e.getMessage());
}
}
检查config.properties是不是在src路径下
你试试把资源文件放在src/main/resources文件夹下,注意是源文件夹,不是普通文件夹
prop.load(JDBCUtils.class.getResourceAsStream("config.properties"));
可能就是路径放错了,我也遇到了创建文件夹再放文件反而失败,直接在工程下放文件反而可以执行的情况。