BaseDao的增删改查

一.BaseDao是什么

BaseDao是为了解决数据库中增删改查而的提供的一个定义类!

二.BaseDao的操作

1、连接数据库

 private String driver = "com.mysql.cj.jdbc.Driver";// 数据库驱动字符串
    private String url = "jdbc:mysql://localhost:3306/20240322db?serverTimezone=GMT%2B8";// 连接URL字符串
    private String user = "root"; // 数据库用户名
    private String password = "root"; // 用户密码
    Connection conn = null;				// 数据连接对象

2、数据库连接异常和关闭连接

//数据库连接
    public Connection getconnection(){
        Connection con=null;
        try {
            if(conn==null){
                Class.forName(driver);
                con= DriverManager.getConnection(url,user,password);
            }
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace(); //处理连接异常
        }
        return con;
    }


    public void closeAll(Connection conn, PreparedStatement pst,ResultSet rs){
        try {
            if(rs!=null){
                rs.close();
            }
            if(pst!=null){
                pst.close();
            }
            if(conn!=null){
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

3、增删改可共用同一个方法

参数解释:
sql:SQL表达式
objs:一个获取值的数组(例:可能改一个值,也有可能改多个值)

public int Update(String sql,Object []objs){
        int row=0;
        Connection conn=getconnection();
        try {
            //预处理对象
            PreparedStatement pst=conn.prepareStatement(sql);
            //数据注入
            for (int i = 0; i < objs.length; i++) {
                pst.setObject(i+1,objs[i]);
            }
            //处理数据
            row=pst.executeUpdate();
            //释放资源
            closeAll(conn,pst,null);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row;
    }

4、查询方法

按需求写查询方法!

public List<Bao> select(){ //针对查询方法
        List<Bao> lis=null;
        Connection conn=getconnection();
        String sql="select * from t_user";
        ResultSet rs=null;
        PreparedStatement pst=null;
        try {
            //预处理对象
            pst=conn.prepareStatement(sql);
            rs=(ResultSet) pst.executeQuery();
            while (rs.next()){
                Bao b=new Bao();
                b.setId(rs.getInt("id"));
                b.setName(rs.getString("name"));
                b.setPassword(rs.getString("password"));
                b.setAge(rs.getInt("age"));
                lis.add(b);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            this.closeAll(conn,pst,rs);
        }
        return lis;
    }

总结:这是比较简单的java连接数据库,可用于jsp等等

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值