在java中要实现和MySql的更方便的连接以及保证安全,那么配置文件必不可少。下面我就献上,我认为一招鲜吃遍天搞定配置文件的方法。
首先要知道,很多公司为了保证数据库的安全性,对于账户明和密码都是定时更新的,如果在JDBC中将用户名和密码定死,那么后期修改起来就变得异常的麻烦。为了解决这个问题,引出了配置文件的存在。
首先在src下建立一个名字为user,后缀为properties的文件。紧接着把帐户名、密码、JDBC协议放进去。
db.username=root
db.password=123456
db.url=jdbc:mysql://localhost:3306/demo?useSSL=false&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8
db.driverClassName=com.mysql.jdbc.Driver
/*
?useSSL=false&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8
这一串是url的几个参数。第一个是设置时区的;后面的是设置字符集格式,防止出现插入中文字段出现乱码的。
*/
public class JdbcUtil {
private static Properties properties = new Properties();
static
{
//写一个类需要动态的获取某个文件的位置,从而能够获取此文件的资源
InputStream res = JdbcUtil.class.getResourceAsStream("/user.properties");
try {
//加载信息到集合中
properties.load(res);
} catch (IOException e) {
//转换成运行时异常,可以抛出
throw new RuntimeException(e);
} finally {
if(res!=null){
try {
res.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//以下个人认为可写可不写
properties.getProperty("db.username");
properties.getProperty("db.password");
properties.getProperty("db.url");
properties.getProperty("db.driverClassName");
}
//连接
public static Connection getConnection() throws SQLException {
Connection connection = DriverManager.getConnection(properties.getProperty("db.url"), properties.getProperty("db.username"), properties.getProperty("db.password"));
//返回一个连接对象
return connection;
}
}