JDBC之增删改查的封装笔记

news/2024/5/19 0:49:21 标签: jdbc

文章目录

  • 准备工作
  • 对增删该查的封装
  • 用法

准备工作

    // 保存静态的连接
    private static Connection connection =null;
    static {
        try {
            // 静态加载mysql驱动
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 防止用户创建实例
     */
    private DBAccess(){}

    /**
     * 获取类的实例
     * @param dbURL 数据源
     * @param dbName 数据库名称
     * @param user 用户
     * @param password 密码
     * @return 类的单例
     */
    public static DBAccess getInstance(String dbURL, String dbName, String user, String password){
        getInstance(dbURL, dbName, user, password);
        return InnerClass.dbAccess;
    }
    static class InnerClass{
         static DBAccess dbAccess = new DBAccess();
    }
    // 获取或更新数据库的连接
    protected static Connection getConnection(String dbURL, String dbName, String user, String password){
            try {
                if (connection == null || connection.isClosed())
                    connection = DriverManager.getConnection(String.format("jdbc:mysql://%s:3306/%s?user=%s&password=%s", dbURL, dbName, user, password));
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return connection;
    }

对增删该查的封装

    /**
     * 增、改、删
     * @param sql
     * @param objects
     * @return 修改的记录条数
     */
    public int insertOrUpdateOrDelete(String sql, Object[] objects){
        PreparedStatement preparedStatement = null;
        int count = 0;
        try {
            preparedStatement = connection.prepareStatement(sql);
            if (objects != null){
                for (int i = 0; i < objects.length; i ++){
                    preparedStatement.setObject(i + 1, objects[i]);
                }
            }
            count = preparedStatement.executeUpdate();
            preparedStatement.close();
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }

    /**
     * 查询
     * @param sql
     * @return 结果集
     */
    public ResultSet find(String sql, Object[] objects){
        ResultSet set = null;
        PreparedStatement preparedStatement = null;
        List<Worker> list = null;
        try{
            preparedStatement =  connection.prepareStatement(sql);
            if (objects != null){
                for (int i = 0; i < objects.length; i ++){
                    preparedStatement.setObject(i + 1, objects[i]);
                }
            }
            set = preparedStatement.executeQuery(sql);
            preparedStatement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return set;
    }

用法

 /**
     * 插入员工
     * @param worker
     * @return
     */
    public int addWorker(Worker worker){
        DBAccess dao = DBAccess.getInstance("localhost", "demo", "root", "root");
        Object[] objects = {worker.getName(), worker.getSex(), worker.getAge(), worker.getPosition(), worker.getTel()};
        return dao.insertOrUpdateOrDelete("insert into worker values(null, ? , ? ,?, ?, ?)", objects);
    }

    /**
     * 删除员工
     * @param workerId
     * @return
     */
    public int deleteWorker(int workerId){
       DBAccess dao = DBAccess.getInstance("localhost", "demo", "root", "root");
        return dao.insertOrUpdateOrDelete("delete from worker where id=?", new Object[]{workerId});
    }

    /**
     * 查询所有员工
     * @return
     */
    public ResultSet getAllWorker(){
        DBAccess dao = DBAccess.getInstance("localhost", "demo", "root", "root");
        return dao.find("select * from worker", null);
    }

    /**
     * 更新表数据
     * @param worker
     * @return
     */
    public int updateWorker(Worker worker){
        DBAccess dao = DBAccess.getInstance("localhost", "demo", "root", "root");
        Object[] objects={worker.getName(), worker.getSex(), worker.getAge(), worker.getPosition(), worker.getTel()};
        return dao.insertOrUpdateOrDelete("update worker set name=?, sex=?, age=?, position=?, tel=?", objects);
    }

http://www.niftyadmin.cn/n/1152311.html

相关文章

虚拟机加硬盘做逻辑卷

lsblk 查看已经添加的新硬盘&#xff08;sdb&#xff09; lsblk NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT fd0 2:0 1 4K 0 disk sda 8:0 0 100G 0 disk ├─sda1 8:1 0 500M 0 part /boot └─sda2 …

Istio - CricuitBreaker - OutlierDetection

Istio中关于CircuitBreaker&#xff08;断路器&#xff09;的定义在DestiantionRule中&#xff0c; 关于Istio中CircuitBreaker官方文档如下&#xff1a; https://istio.io/docs/tasks/traffic-management/circuit-breaking/ https://istio.io/docs/reference/config/networ…

vue学习,制作扫雷游戏

文章目录准备工作引入vue.jshtml、css游戏完整代码&#xff08;附详细注释&#xff09;运行效果图准备工作 引入vue.js <!-- cdn方式&#xff0c;调用vue的官方js --> <script src"https://cdn.jsdelivr.net/npm/vue2.6.10/dist/vue.js"></script&g…

关于大型网站技术演进的思考(三)--存储的瓶颈(3)

存储的瓶颈写到现在就要进入到深水区了&#xff0c;如果我们所做的网站已经到了做数据库垂直拆分和水平拆分的阶段&#xff0c;那么此时我们所面临的技术难度的挑战也会大大增强。这里我们先回顾下数据库的垂直拆分和水平拆分的定义&#xff1a;垂直拆分&#xff1a;把一个数据…

Isito - Rate Limits(请求限速)

Istio官方文档&#xff1a; https://istio.io/docs/tasks/policy-enforcement/rate-limiting/ https://istio.io/docs/tasks/policy-enforcement/enabling-policy/ 在进行rateLimits测试开始之前&#xff0c;需要先确保 Enabling Policy Enforcement&#xff08;开启Mixer策…

安装less/sass

安装sass npm i node-sass安装wepy-compiler-sass插件 npm install wepy-compiler-sass --save-dev在我的项目中使用才有用。 转载于:https://www.cnblogs.com/dashucoding/p/11140245.html

vue学习,设计一个测试前后端分离开发时的测试工具

文章目录why&#xff1f;what?how?工具效果&#xff1a;工具代码&#xff1a;why&#xff1f; 在使用vue-cli进行前后端项目分离开发时&#xff0c;每次测试&#xff0c;我都需要将vue项目build成一个文件放入web项目中&#xff0c;因此我在开发前端时&#xff0c;会用静态数…

(错误记录)Vue: Unknown custom element

错误&#xff1a; vue.js:634 [Vue warn]: Unknown custom element: <ve-pie> - did you register the component correctly? For recursive components, make sure to provide the "name" option. 原因&#xff1a;引用了插件&#xff0c;却没有在main.js里使…