2

我编写了一个代码以从 servlet 连接到数据库。我想使用属性。但它不起作用。我认为我的代码或属性文件有问题。请帮助我更正它。

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(drivers);
            con=DriverManager.getConnection(connectionURL,username,password);
            System.out.println("Connection Successful");

..

这是我的属性文件

jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@192.168.101.84:1521:orcl
jdbc.username=user1
jdbc.password=123
4

4 回答 4

1

代替

FileInputStream in = new FileInputStream(System.getProperty("WEB-INF/dbConnection.properties"));

利用

InputStream in = getClass().getResourceAsStream("dbConnection.properties");
于 2013-07-23T07:54:45.473 回答
1
try  {
    FileReader reader = new FileReader("Full Path");
    Properties prop = new Properties();
    prop.load(reader);

    String drivers = prop.getProperty("jdbc.driverClassName");
    String connectionURL = prop.getProperty("jdbc.url");
    String username = prop.getProperty("jdbc.username");
    String password = prop.getProperty("jdbc.password");
    Class.forName(drivers);
    Connection con = DriverManager.getConnection(connectionURL, username, password);
    System.out.println("Connection Successful");
} catch (SQLException sqle) {
    // TODO: Add catch code
    sqle.printStackTrace();
} catch (FileNotFoundException fnfe) {
    // TODO: Add catch code
    fnfe.printStackTrace();
} catch (IOException ioe) {
    // TODO: Add catch code
    ioe.printStackTrace();
} catch (ClassNotFoundException cnfe) {
    // TODO: Add catch code
    cnfe.printStackTrace();
}catch (Exception e) {
    // TODO: Add catch code
    e.printStackTrace();
}
于 2018-11-17T09:51:37.063 回答
0

这部分:

(System.getProperty("WEB-INF/dbConnection.properties")); 

实际上是指您的类路径,请尝试删除WEB-INF/或仅离开/,以检查根文件夹。

或者您可以指定完全限定名称,即:"C:\\foo\\test\\...\\dbConnection.properties""/app/blah/.../dbConnectionProperties"

于 2013-07-23T08:54:06.043 回答
0

对于类名,在属性文件中您已将驱动程序定义为“jdbc.driverClassName”

但是当传递变量时,你只是传递为'jdbc.drivers'

于 2014-08-29T10:49:41.167 回答