java 在java中读取dbConnection.properties文件以使用eclipse连接到数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11534680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
reading dbConnection.properties file in java to connect to database using eclipse
提问by sonam
I have create a dbConnection.properties file and placed it into WEB-INF. To read that file and connect to database I hava written a class as
我创建了一个 dbConnection.properties 文件并将其放入 WEB-INF。要读取该文件并连接到数据库,我编写了一个类
public class DbConnection {
public static Connection connection()
{
Connection con=null;
//String connectionURL = "jdbc:mysql://localhost:3306/demo";
try
{
Properties prop=new Properties();
FileInputStream in = new FileInputStream(System.getProperty("WEB-INF/dbConnection.properties"));
prop.load(in);
in.close();
String drivers = prop.getProperty("jdbc.drivers");
String connectionURL = prop.getProperty("jdbc.url");
String username = prop.getProperty("jdbc.username");
String password = prop.getProperty("jdbc.password");
//Class.forName("com.mysql.jdbc.Driver").newInstance();
Class.forName(drivers);
con=DriverManager.getConnection(connectionURL,username,password);
System.out.println("Connection Successful");
return con;
}
catch(Exception e)
{
System.out.println("error !!");
}
return null;
}
}
}
Its going into catch block. How can i read .properties file?
它进入catch块。我如何读取 .properties 文件?
回答by Patton
Place the properties file under src
if you are using eclipse or WEB-INF/classes
if you are using ant or gradle or any other tool for that matter and then modify the statement
src
如果您使用的是 eclipse 或者WEB-INF/classes
您使用的是 ant 或 gradle 或任何其他与此相关的工具,请将属性文件放在下面,然后修改语句
FileInputStream in = new FileInputStream(System.getProperty("WEB-INF/dbConnection.properties"));
prop.load(in);
with
和
prop.load(DbConnection.class.getClassLoader()
.getResourceAsStream("dbConnection.properties"));
Make this changes and it will work!
进行此更改,它将起作用!