MySQL的数据访问和DAO模式

技术博客

Properties 配置文件

在不同业务场景的实际开发过程中,数据库服务器的 IP 地址,访问数据库的用户名或密码经常会发生变化,维护和修改比较麻烦,而为了避免这种情况,Java 中有一个比较重要的 Properties 类,它可以读取 Java 配置文件,这样就可以把常用的配置信息卸载配置文件中,程序员进行维护和修改。

  1. 添加 .properties 文件

选择 src 文件夹并右击,New → File,命名为 database.properties

img

  1. 编辑配置文件
 driver=com.mysql.cj.jdbc.Driver
 url=jdbc:mysql://localhost:3306/hospital?serverTimezone=GMT-8
 username=root
 password=123456

格式无需分号结尾,与Java中的Map结构相似,等号之前是键,等号之后是只。在一个配置文件中,键应该唯一,但值可以不唯一,通过一个键就可以找到确定值。

  1. 读取配置文件

使用java.util包下的 Properties类读取配置文件。

Properties 类继承自Hashtable类,其常用方法如下:

方法 描述
String getProperty (String key) 用指定的键在此属性列表中搜索属性
Object setProperty(String key, String value) 通过调用基类 Hashtable 的 put() 方法设置键-值对
void load(InputStream streamIn) throws IOException 从输入流中读取属性列表(键和元素对)
void clear() 清除所装载的键-值对,该方法由基类 Hashtable 提供

DAO

简介

DAO (DataAccessobjects) 数据存取对象是指位于业务逻辑和持久化数据之间,实现对持久化数据的访问的工作模式。

通俗来讲,就是将数据库操作都封装起来,对外提供相应的接口。

DAO的优势

  1. 提高代码的复用性

  2. 隔离性

    1. 隔离了数据访问代码和业务逻辑代码
    2. 隔离了不同数据库实现
  3. 易维护

DAO 的组成

  1. 数据库连接和关闭工具类:避免了数据库连接和关闭代码的重复使用,方便修改。
  2. 实体类:用于存放与传输对象数据。
  3. DAO 接口:把对数据库的所有操作定义成抽象方法,可以提供多种实现
  4. DAO 实现类:针对不同数据库给出DAO接口定义方法的具体实现。

工具类 连接数据库

 package cn.hospital.dao;
 ​
 import java.io.IOException;
 import java.io.InputStream;
 import java.sql.*;
 import java.util.Properties;
 ​
 /**
  * 数据库通用工具类 即基类
  */
 public class Dao {
     private Connection conn;
     private PreparedStatement ps;
     private static String driver;
     private static String url;
     private static String userName;
     private static String pwd;
     
     // 省略封装
 ​
     static{
         init();
     }
 ​
     public static void init(){
         //创建 Properties 对象
         Properties pt = new Properties();
         String filePath = "database.properties";
         InputStream is = Dao.class.getClassLoader().getResourceAsStream(filePath);
         try {
             pt.load(is);
             //根据键来获取对应的值
             driver = pt.getProperty("driver");
             url = pt.getProperty("url");
             userName = pt.getProperty("user");
             pwd = pt.getProperty("pwd");
         } catch (IOException e) {
             e.printStackTrace();
         }
     }
 ​
     public Connection getConnection(){
         if(conn == null) {
             try {
                 // 1.加载驱动
                 Class.forName(getDriver());
                 // 2.获取连接
                 conn = DriverManager.getConnection(getUrl(),getUserName(),getPwd());
             } catch (ClassNotFoundException | SQLException e) {
                 e.printStackTrace();
             }
         }
         return conn;
     }
 ​
     /**
      * 关闭
      * @param rs 结果集
      * @param ps 接口
      * @param conn 数据库连接
      */
     public void closeAll(ResultSet rs , PreparedStatement ps , Connection conn){
         if(null!= rs){
             try {
                 rs.close();
             } catch (SQLException e) {
                 e.printStackTrace();
             }
         }
 ​
         if(null!= ps){
             try {
                 ps.close();
             } catch (SQLException e) {
                 e.printStackTrace();
             }
         }
 ​
         if(null!= conn){
             try {
                 conn.close();
             } catch (SQLException e) {
                 e.printStackTrace();
             }
         }
     }
 ​
     public int executeUpdate(String sql , Object ... prams){
         // 受影响的行数
         int result = 0;
         // 1.获取连接
         conn = getConnection();
         try {
             // 2.发送sql语句
             ps = conn.prepareStatement(sql);
             // 3.判断是否有参数
             if (prams != null) {
                 // 4.循环遍历参数
                 for (int i = 0; i < prams.length;i++){
                     ps.setObject(i+1,prams[i]);
                 }
                 // 5.执行 返回受影响的行数
                 result = ps.executeUpdate();
             }
         } catch (SQLException e) {
             e.printStackTrace();
         }
         return result;
     }
     
 }

或者

菜鸟教程 —— 连接数据库

 public class BaseDao {
     private static String driver="com.mysql.jdbc.Driver";
     private static String url="jdbc:mysql://127.0.0.1:3306/epet";
     private static String user="root";
     private static String password="root";
         static {
             try {
                 Class.forName(driver);
             } catch (ClassNotFoundException e) {
                 e.printStackTrace();
             }
         }
         
     public static Connection getConnection() throws SQLException {
         return DriverManager.getConnection(url, user, password);    
     }
     
     public static void closeAll(Connection conn,Statement stmt,ResultSet rs) throws SQLException {
         if(rs!=null) {
             rs.close();
         }
         if(stmt!=null) {
             stmt.close();
         }
         if(conn!=null) {
             conn.close();
         }
     }
     
 ​
     public int executeSQL(String preparedSql, Object[] param) throws ClassNotFoundException {
         Connection conn = null;
         PreparedStatement pstmt = null;
         /* 处理SQL,执行SQL */
         try {
             conn = getConnection(); // 得到数据库连接
             pstmt = conn.prepareStatement(preparedSql); // 得到PreparedStatement对象
             if (param != null) {
                 for (int i = 0; i < param.length; i++) {
                     pstmt.setObject(i + 1, param[i]); // 为预编译sql设置参数
                 }
             }
         ResultSet num = pstmt.executeQuery(); // 执行SQL语句
         } catch (SQLException e) {
             e.printStackTrace(); // 处理SQLException异常
         } finally {
             try {
                 BaseDao.closeAll(conn, pstmt, null);
             } catch (SQLException e) {    
                 e.printStackTrace();
             }
         }
         return 0;
     }
     
 }

实体类

 package entity;
 ​
 import java.util.Date;
 ​
 /**
  * 实体类
  */
 public class Hospital {
     private int patientID;
     private String patientName;
     private String password;
     private Date birthDate;
     private String gender;
     private String phoneNum;
     private String email;
     private String identityNum;
     private String address;
     
     // 省略封装、无参有参
 }

DAO 接口

 package cn.hospital.dao;
 ​
 import entity.Hospital;
 import java.util.List;
 ​
 public interface HospitalDao {
     /**
      * 添加数据
      */
     public int addPaitent(Hospital h);
     
     /**
      * 根据 id 删除表中数据
      */
     public int deletePaitent(int id);
 ​
     /**
      * 更新值
      */
     public int updatePaitent(Hospital h);
 ​
     /**
      * 查询检查表中的信息
      */
     public List<Hospital> getHospitalList();
 }
 ​

DAO 实现类

 package cn.hospital.dao.impl;
 ​
 import cn.hospital.dao.Dao;
 import cn.hospital.dao.HospitalDao;
 import entity.Hospital;
 ​
 import java.sql.Connection;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.Date;
 import java.sql.SQLException;
 import java.util.ArrayList;
 ​
 import java.util.List;
 ​
 /**
  * DAO 实现类
  */
 public class HospitalDemo extends Dao implements HospitalDao {
 ​
     @Override
     public int addPaitent(Hospital h) {
         String sql = "insert into patient(patientName, password, birthDate, gender, phoneNum, email, identityNum, address) " +
                      "values(?,?,?,?,?,?,?,?)";
         return this.executeUpdate(sql,h.getPatientName(),h.getPassword(),h.getBirthDate(),h.getGender(),h.getPhoneNum(),h.getEmail(),h.getIdentityNum(),h.getAddress());
     }
 ​
     @Override
     public int deletePaitent(int id) {
         String sql = "delete from patient where patientID = ?";
         return this.executeUpdate(sql,id);
     }
 ​
     @Override
     public int updatePaitent(Hospital h) {
         String sql = "update patient set patientName = ? where patientName = '张三'";
         return this.executeUpdate(sql,h.getPatientName());
     }
 ​
     /**
      * 查询检查表中的信息
      */
     @Override
     public List<Hospital> getHospitalList() {
         Connection conn = null;
         PreparedStatement ps = null;
         ResultSet rs = null;
         List<Hospital> list = new ArrayList<>();
         String sql = "select * from patient";
         try {
             // 1.获取连接
             conn = getConnection();
             // 2.发送sql
             ps = conn.prepareStatement(sql);
             // 3.执行sql
             rs = ps.executeQuery();
             // 4.循环遍历输出
             while (rs.next()){
                 //创建 hospital对象,用来存储查询德信息
                 Hospital hospital = new Hospital();
                 hospital.setPatientID(rs.getInt("patientID"));
                 hospital.setPatientName(rs.getString("patientName"));
                 hospital.setBirthDate(rs.getDate("birthDate"));
                 hospital.setPassword(rs.getString("password"));
                 hospital.setGender(rs.getString("gender"));
                 hospital.setPhoneNum(rs.getString("phoneNum"));
                 hospital.setEmail(rs.getString("email"));
                 hospital.setIdentityNum(rs.getString("identityNum"));
                 hospital.setAddress(rs.getString("address"));
                 //将对象添加到集合中
                 list.add(hospital);
             }
         } catch (SQLException e) {
             e.printStackTrace();
         } finally {
             this.closeAll(rs,ps,conn);
         }
         return list;
     }
 }
posted @ 2022-05-20 17:02  JanYork(小简)  阅读(76)  评论(0编辑  收藏  举报