1. 抽取一个工具类。 BaseDao
Userdao类中公共的代码抽取到该类中。提高代码的重用性。
2. 把数据库的信息抽取到properties文件
(1)在src根目录下创建一个db.properties
# =后不能使用“ ”
username=root #root后不能加空格
password=root
driverName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/world?serverTimezone=Asia/Shanghai
(2) 读取属性文件中的内容
public Connection connection;
public PreparedStatement preparedStatement;
public ResultSet resultSet;
private static String username;
private static String password;
private static String driverName;
private static String url; //定义字符串来接收db.properties 里的username,password,driverName,url 数据
InputStream inputStream = Basedao.class.getResourceAsStream("/db.properties");
Properties properties = new Properties();
try {
properties.load(inputStream);
username = properties.get("username").toString(); //获取/db.properties的userName数据
password = properties.get("password").toString(); //获取/db.properties的password数据
driverName = properties.get("driverName").toString(); //获取/db.properties的driverName数据
url = properties.get("url").toString(); //获取/db.properties的url数据
Class.forName(driverName); //加载驱动
} catch (Exception e) {
e.printStackTrace();
}
4. BaseDao 增删改抽取
//增删改的公共方法
public int update(String sql,Object... params){
try {
getConnection();
ps = connection.prepareStatement(sql);
//为占位符赋值
for (int index=0;index<params.length;index++){
ps.setObject(index+1,params[index]);
}
int i = ps.executeUpdate();
return i;
}catch (Exception e){
e.printStackTrace();
}finally {
closeAll();
}
return 0;
}
5. 完整代码如下
//抽取BaseDao父类
public class BaseDao{
//数据库的对象
public Connection connection;
public PrepareStatement ps;
public ResultSet resultSet;
//数据库连接信息
public static String driverName; //驱动名称
public static String url;//数据库路径
public static String username;
public static String password;
//读取数据库连接信息和加载驱动
static{
InputStream resourceAsStream =BaseDao.class.getResourceAsStream("/属性文件的路径");
Properties properties=new Properties();
properties.load(resourceAsStream);
driverName=properties.get("driverName"); //driverName要和属性文件的key对应
url=properties.get("url"); //url要和属性文件的key对应
username=properties.get("username"); //username要和属性文件的key对应
password=properties.get("password"); //password要和属性文件的key对应
Class.forName(driverName);
}
//获取连接对象
public void getConn(){
connection=DriverManager.getConnection(url,username,password);
}
//关闭资源
public void closeAll(){
try {
if (resultSet != null) {
resultSet.close();
}
if (ps != null) {
ps.close();
}
if (connection != null) {
connection.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
//增删改得通用方法
public int update(String sql,Object... params){ //params:占位符参数的值
try{
getConn();
ps=connection.prepareStatement(sql);
//为占位符赋值
for(int i=0;i<params.length;i++){
ps.setObject(i+1,params[i]);
}
//执行sql
int row=ps.executeUpdate();
return row;
}catch(Execption e){
}finally{
closeAll();
}
return 0;
}
}