再网上找的现成的jdbc工具类,我们发现数据库的连接信息都是写进方法的,如果要修改要找到方法取里面修改,这样的后果就是代码显得不"高级",高耦合
为了降低耦合我们可以将url等信息写在一个properties文件里面,读取文件动态赋值
properties文件的格式就是key:value的格式,类似于map
properties文件:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/xxxx?useSSL=false&userUnicode=true&characterEncoding=utf-8
username=root
password=123456
在java中提供了一个专门处理properties文件的类Properties,包括加载,读取这些操作都已经定义好,我们只是调用即可
读取文件代码,用到了静态代码块:
public class DataBase {
private static String driver;
private static String url;
private static String username;
private static String password;
private static Logger logger = LogManager.getLogger();//日志
static {//静态代码块
Properties properties = new Properties();
//通过类加载器读取把文件转化成输入字节流
InputStream in = DataBase.class.getClassLoader().getResourceAsStream("database.properties");
try {
properties.load(in);//读取输入字节流
}catch (IOException e){
e.printStackTrace();
}
driver = properties.getProperty("driver").trim();
url = properties.getProperty("url").trim();
username = properties.getProperty("username").trim();
password = properties.getProperty("password").trim();
logger.info("driver: {}",driver);
logger.info("url: {}",url);
logger.info("username: {}",username);
logger.info("password: {}",password);
}
public static Connection getConnection(){
Connection coon = null;
try{
coon = DriverManager.getConnection(url,username,password);
}catch (SQLException e){
e.printStackTrace();
}
return coon;
}
public static void main(String[] args) {//main方法测试
DataBase.getConnection();
}
}
输出:
连接成功成功