1、定义工具类
public Class DbUtils{
//1.定义工具类需要的对象
protected Connection conn=null;
protected PreparedStatement ps=null;
protected ResultSet rs=null;
protected int k=0;//受影响的行数
private driverName="com.mysql.cj.jdbc.Driver";
private url="jdbc:mysql://localhost:3306/test_db?serverTimezone=UTC";
private userName="root";
private password="123456";
//2.加载驱动
static{
try{
Class.forName(driverName);
}catch(ClassNotFoundException ex){
ex.printStackTrace();
}
}
//3.获得链接
protected Connection getConnection(){
try{
conn=DriverManger.getConnection(url,userName,password);
}catch(SQLException ex){
ex.printStackTrace();
}
return conn;
}
//4.创建通道
protected PreparedStatement getPst(String sql){
try{
getConnection();
ps=conn.preparedStatement(sql);
}catch(SQLException ex){
ex.printStackTrace();
}
return ps;
}
//5.给占位符赋值
protected void setParams(List list){
try{
if(list!=null&&list.size()>0){
for(int i=0;i<list.size();i++){
ps.setObject(i+1,list.get(i));//赋值从参数1开始
}
}
}catch(SQLException ex){
ex.printStackTrace();
}
}
//6.增删改调取的方法
protect int update(String sql,List params){
try{
getPst(sql);
setParams(params);
k=ps.executeUpdate();
}catch(SQLException ex){
ex.printStackTrace();
}
return k;
}
//7.查询的时候调取的方法
protected ResultSet query(String sql,List params){
try{
getPst(sql);
setParams(params);
rs=ps.executeQuery();
return rs;
}catch(SQLException ex){
ex.printStackTrace();
}
return null;
}
//8.关闭资源
protected void closeAll(){
try{
if(rs!=null){
rs.close();
}
if(ps!=null){
ps.close();
}
if(conn!=null){
conn.close();
}
}catch(SQLException ex){
ex.printStackTrace();
}
}
}
2、定义db.properties文件保存数据库配置
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/test_db?serverTimezone
userName=root
password=123456
3、工具类中读取配置文件
使用类加载器
InputStream inputStream=当前类.class.getClassLoader()
.getResourceAsStream("db.properties");
Properties properties=new Properties();
properties.load(inputStream);
driverName=properties.getProperty("driver");
url=properties.getProperty("url");
userName=properties.getProperty("userName");
password=properties.getProperty("password");
使用ResoureBundle读取配置
ResourceBundle rb=ResourceBundle.getBundle("db");
driverName=rb.getString("driver");
url=rb.getString("url");
userName=rb.getString("userName");
password=rb.getString("password");
4、ResourceBundle访问本地资源
在设计时,需要一些适合本地修改的配置信息;如果作为静态变量,那么需要每次都去编译生成class文件;通过ResourceBundle,我们需要访问位于WEB-INF/classes目录下的后缀为.properties的文本类型文件,从里面读取我们需要的值。