1

您好我正在加载一个属性文件来建立数据库连接,例如:

DB1="JDBc................", username , password

上面的行与属性文件中的一样,但是当我调用 getConnection 方法时,我需要发送 url、用户名和密码。我该如何解析它。

4

3 回答 3

8

You can put your key/value pairs in a properties file like this:

dbUrl = yourURL
username = yourusername
password = yourpassword

Then you can load them into your app from the properties file:

private void loadProps() {
    try {
        InputStream is = getClass().getResourceAsStream("database_props.properties");
        props = new Properties();
        props.load(is);
        is.close();
        dbConnStr = props.getProperty("dbUrl");
        username = props.getProperty("username");
        password = props.getProperty("password");
    }
    catch(IOException ioe) {
        log.error("IOException in loadProps");
        for(StackTraceElement ste : ioe.getStackTrace())
        log.error(ste.toString());
    }
}

And then you can use those values to create your connection.

于 2011-01-14T12:12:19.320 回答
1
  1. 您可以拆分条目:

    String dbProperty = prop.getProperty("DB1");   
    String[] dbDetails = dbProperty.split(",", 3);
    

dbDetails[0]将持有你的JDBC...[1]你的username[2]你的password

  1. 更好的是,您可能希望将它们保存在不同的属性中(正如 lweller 所说)

    db.username = scott  
    db.password = tiger  
    db.url = ....
    

通过这种方式,您可以获得更好的清晰度和控制力。

于 2011-01-14T10:27:45.970 回答
0

最好单独定义

dburl =....
username =....
password = ...

还是要解析的话,可以使用string的split方法,用逗号分割

于 2011-01-14T10:31:46.430 回答