美文网首页
java中如何使用.properties文件

java中如何使用.properties文件

作者: picassagirl | 来源:发表于2022-11-19 08:57 被阅读0次

1、在java Resources下的src目录下新建db.properties文件
内容如下:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydb?characterEncoding=utf-8
uname=hello
pwd=56897

2、在java Resources下的util包中的DbHelper.java中输入以下代码,


Properties properties = new Properties();
InputStream iStream = this.getClass().getResourceAsStream("/db.properties");
properties.load(iStream);
//获得集合中的数据
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
String uname = properties.getProperty("uname");
String pwd = properties.getProperty("pwd");
Class.forName(driver);
this.connection=DriverManager.getConnection(url,uname,pwd);

3、代替原来的代码:

Class.forName("com.mysql.jdbc.Driver");
this.connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?characterEncoding=utf-8","hello","56897");
            

4、以后直接修改db.properties中的内容即可实现对不同的数据库的使用

相关文章

网友评论

      本文标题:java中如何使用.properties文件

      本文链接:https://www.haomeiwen.com/subject/bwpmxdtx.html