mysql数据库url,用户名和密码在文件中

时间:2012-03-12 18:53:20

标签: java mysql database jdbc

如何将我的mysql数据库url,用户名和密码放在一个文件中,如何访问它们以在我的java代码中使用而不是硬编码。我试过谷歌,但没有明确的方向

2 个答案:

答案 0 :(得分:3)

创建properties file。您可以按the Properties API加载它。

E.g。 config.properties

url = jdbc:mysql://localhost:3306/dbname
username = foo
password = bar

然后你可以按如下方式加载和读取它(在你把它放在类路径中之后):

Properties config = new Properties();
config.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties"));

String url = config.getProperty("url");
String username = config.getProperty("username");
String password = config.getProperty("password");
// ...

答案 1 :(得分:0)

 /**
 * Function that connects to a DB and data fro connection is loaded from a    properties file
 * @param fileName
 * @return the connection to DB or null if any problem
 */
public java.sql.Connection connect_to_database_from_properties(String fileName)
{
    Properties prop = new Properties();

    InputStream is;
    try {
        is = new FileInputStream(fileName);

    prop.load(is);
    String url=prop.getProperty("url");
    String un=prop.getProperty("username");
    String pass=prop.getProperty("password");
    System.out.println("URL: "+url+"  UN:  "+un+"  PASS:  "+pass);
    is.close();
    Class.forName("com.mysql.jdbc.Driver"); 

    java.sql.Connection conection =DriverManager.getConnection(url, un, pass);
    return conection;

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;

}