• JDBC---封装JDBC代码,配置properties文件


    封装JDBC

    由于在使用jdbc连接数据库时,出现了多次下列代码

    //注册驱动获取地址
    Class.forName("com.mysql.jdbc.Driver");
    String url = "jdbc:mysql://localhost:3306/tb1?characterEncoding=utf-8";
    String username = "root";
    String password = 自己的密码;
    //获取数据库连接
    Connection conn = DriverManager.getConnection(url, username, password);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    存在大量数据冗余,所以可以将该代码提取出来,封装成一个工具类,在使用时只需传入sql语句以及sql代码中 ? 的数量即可

    封装代码:

    /**
     * 数据库工具类
     */
    public class BaseDao {
        Connection conn = null;
        PreparedStatement ps = null;
        //获取Conn对象 打开数据库链接
        public boolean getConn() {
            boolean bool = false;//默认 false 未打开数据库
            try {
                //加载驱动  方言
                Class.forName("com.mysql.jdbc.Driver");
                //准备数据库连接路径
                String url = "jdbc:mysql://127.0.0.1:3306/xxshop?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull";
                //用户名与密码
                String username = "root";
                String userpwd = "密码";
                //根据路径,用户名,密码 使用DriverManager获取数据库connection连接
                conn = DriverManager.getConnection(
                        url,username,userpwd);
                bool = true;//已经打开
            } catch (Exception e) {
                e.printStackTrace();
                bool = false ;//已经打开
            }
                return  bool;
        }
        /**
         * 添加,修改,删除数据
         * @param sql
         * @param objs
         * @return
         */
        public int executeUpdate(String sql,Object objs[])
        {
            int res = 0;//初始化执行结果  失败0
            try {
                if(getConn())//打开数据库链接
                {
                    ps = conn.prepareStatement(sql);
                    if(objs!=null){
                        for (int i = 0; i < objs.length; i++) {
                            ps.setObject((i+1),objs[i]);
                        }
                    }
                    res = ps.executeUpdate();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                closeResource();//关闭数据源
            }
            return res;
        }
        /**
         * 查询
         * @param sql
         * @param objs
         * @return
         */
        public ResultSet executeSQL(String sql,Object objs[]){
            ResultSet rs = null;
            try {
                if(getConn())//打开数据库链接
                {
                    ps = conn.prepareStatement(sql);
                    //判断是否有参数
                    if (objs != null) {
                        //循环封装参数
                        for (int i = 0; i < objs.length; i++) {
                            ps.setObject((i + 1), objs[i]);
                        }
                    }
                    rs = ps.executeQuery();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                closeResource();//释放资源
            }
            return rs;
        }
        //关闭资源
        public void closeResource(){
            try {
                if(ps!=null)
                {
                    ps.close();
                }
                if(conn!=null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97

    由于在开发过程中,后续使用时数据库文件不可能写死到java代码中,多使用 yml 或者 properties 文件来存储数据库信息,所以我们将数据库url以及用户名密码提取出来,使用其他方式来读取
    示例代码:
    jdbc.properties:

    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/tb1?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
    username=root
    pwd=密码
    
    • 1
    • 2
    • 3
    • 4

    编写读取类,读取数据库信息

    package JDBC02.util;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Properties;
    
    /**
     * 使用单例模式将文件中的信息提取出来
     * 每次使用这个类时,只new一次
     */
    public class ConfigManager {
    
        private static Properties pro = null;
        private static ConfigManager cm = new ConfigManager();
    
        public ConfigManager() {
            pro = new Properties();
            InputStream is = ConfigManager.class.getClassLoader().getResourceAsStream("jdbc.properties");
            try {
                pro.load(is);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        public static Properties getProperties() {
            return pro;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    修改工具类中的加载数据库信息代码,不再写死

     /**
         * 获取数据库连接驱动
         */
        public static boolean getConn() {
            boolean bool = false;//默认 false 未打开数据库
            try {
                Properties pro = ConfigManager.getProperties();
                String driver = pro.getProperty("driver");
                String url = pro.getProperty("url");
                String username = pro.getProperty("username");
                String pwd = pro.getProperty("pwd");
    
                Class.forName(driver);
                //获取数据库连接
                conn = DriverManager.getConnection(url, username, pwd);
                bool = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return bool;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    这样子可以方便后续的修改以及阅读。

  • 相关阅读:
    git的使用
    Three.js 性能监视器 Stats
    华为OD机试真题-数组拼接-2023年OD统一考试(B卷)
    中国城镇化时空分异及影响因素数据集(2010-2020)
    Golang不同平台编译的思考
    年底了,准备跳槽的可以看看
    公考求的是稳定,搞IT求的是高薪,鱼和熊掌能否兼得?
    MySQL调优之show profile 应用
    五个很实用的IDEA使用技巧
    java中文件流类型输入流InputStream和Byte数组还有File类型对象的区别?(经典)
  • 原文地址:https://blog.csdn.net/qq_57480977/article/details/126948908