我试图使用类加载器获取数据库连接但它总是显示空值,但是当我使用FileInputStream类时,连接已经建立,请指导我做了什么错误
package com.soft.dbconnection;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class Connector {
private static Connection con;
// static FileInputStream input;
static InputStream input = null;
public static Connection getConnection() {
if (con != null) {
return con;
} else {
try {
Properties p = new Properties();
// input = new FileInputStream("F:/workspace/Programs/com.test.soft/src/db.properties");
input = Connector.class.getClassLoader().getResourceAsStream(
"/com.test.soft/src/db.properties");
p.load(input);
String Driver = p.getProperty("driver");
String URL = p.getProperty("url");
String Uname = p.getProperty("uname");
String Password = p.getProperty("password");
Class.forName(Driver);
con = DriverManager.getConnection(URL, Uname, Password);
return con;
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException n) {
System.out.println(n);
} catch (IOException e) {
e.printStackTrace();
}
}
return con;
}
public static void main(String[] args) {
System.out.println(Connector.getConnection());
}
}
答案 0 :(得分:2)
我认为您混淆项目的路径会被打破,以及项目构建后可用的内容
我认为你会发现“/db.properties”或“db.properties”会起作用......
你永远不应该从程序中引用“src”,因为“src”一旦构建就不会存在