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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 05:28:49  来源:igfitidea点击:

reading dbConnection.properties file in java to connect to database using eclipse

javadatabase

提问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 srcif you are using eclipse or WEB-INF/classesif 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!

进行此更改,它将起作用!