Java JDBC工具类的创建

一、JDBC的工作过程

  1. 工作过程

1.1导入驱动

这里主要采用反射的方式,通过Class.forname方法。

1.2获取数据库链接对象

获取到comection的实例之后,搭建起程序与数据库的链接关系。

1.3获取Statement,执行sql语句

生成preparedstatement对象,执行sql语句。

二、创建过程

  1. 引入mysql-connector类库

将下载好的mysql-connector复制粘贴到项目文件中

右击选择 Build Path——Add to Build Path

创建好后,项目文件夹中会新增类库

  1. 创建JDBC工具类

2.1添加工具类的属性

private String url = "jdbc:mysql://localhost:3306/topic?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
    private String user = "root";//
    private String passwd = "123";
    
    private Connection c;
    private PreparedStatement pst;
    private ResultSet rs;

url对应的是数据库的位置

private String url = "jdbc:mysql://localhost:3306/topic?useUnicode=true&characte

2.2获取数据库链接对象

/**
     * 获取数据库连接对象
     * @return
     * @throws Exception
     */
    private Connection getConnect() throws Exception {
        if((this.c == null)) {
            Class.forName("com.mysql.cj.jdbc.Driver");//注册驱动
            this.c = DriverManager.getConnection(url, user, passwd);
        }
        return c;
    }

2.3获取执行sql的preparedStatement对象

/**
     * 获取执行sql的preparedStatement对象
     * @param sql
     * @return
     * @throws Exception
     */
    private PreparedStatement getPreparedStatement(String sql) throws Exception {
        this.pst = getConnect().prepareStatement(sql);
        return pst;
    }

2.4更新数据库方法

protected int update(String sql) throws Exception{
        int i = 0;
        PreparedStatement pst = getPreparedStatement(sql);
        i = pst.executeUpdate();
        //this.closeAll();
        return i;
    }

2.5查询的方法

/**
     * 查询的方法
     * @param sql
     * @return
     * @throws Exception
     */
    protected ResultSet find(String sql) throws Exception{
        PreparedStatement pst = getPreparedStatement(sql);
        rs = pst.executeQuery();
        return rs;
    }

2.6释放资源

/**
     * 释放资源
     */
    public void closeAll() {
        try {
            if(this.rs != null) {
                this.rs.close();
            }
            if(this.pst != null){
                this.pst.close();
            }
            if(this.c != null) {
                this.c.close();
            }
            this.c = null;
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值