-
回顾
- 防止sql得注入---->使用PrepareStatement完成预编译,sql可以使用?占位符。
- Dao模式。—java的一个实体类对应数据库的一张表。 实体类中的属性对应数据库中字段 实体类对象对应数据库的记录。
DAO类对数据库表进行相应的CRUD.
-
正文
1、 抽取一个工具类。 DbUtil.
-
把数据库的信息抽取到properties文件
(1)在src根目录下创建一个db.properties
# =后不能使用“ ”
username=root
password=root
driverName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/world?serverTimezone=Asia/Shanghai
(2) 读取属性文件中的内容
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;
}
-
总结
//抽取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; }
}