从零开始学JDBC--1.5 DML代码抽取,结构简化

根据上节DML的代码,我们将每次执行sql语句时重复的代码抽取出来


  形成了一个静态代码块(注册驱动程序)和2个方法getConnection() – 用于获取连接,
close(Connection conn,Statement stmt) – 用于关闭连接资源

  将其封装在一个类中,JdbcUtil工具类应声而出,代码如下:

/**
 * jdbc工具类
 * 
 * @author llj
 * 
 */
public class JdbcUtil {
    private static String url = "jdbc:mysql://localhost:3306/day17";
    private static String user = "root";
    private static String password = "123";

    /**
     * 将注册驱动程序放在静态代码块中
     */
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("jdbc驱动程序注册失败!");
        }
    }

    /**
     * 抽取获取连接对象的方法
     */
    public static Connection getConnection() {
        try {
            return DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 释放资源的方法
     */
    public static void close(Connection conn,Statement stmt){
        if(stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    }

}

用上面的工具类,我们写一个测试用例:

    @Test
    public void testInsert() {
        Connection conn = null;
        Statement stmt = null;
        try {

            conn = JdbcUtil.getConnection();
            // 3.创建statment
            stmt = conn.createStatement();

            // 4.准备sql
            String sql = "INSERT INTO student (NAME,gender)VALUES('齐八','女')";

            // 5.执行sql语句,得到返回结果
            int count = stmt.executeUpdate(sql);

            // 6、获取返回结果
            System.out.println("本次执行共影响了:" + count + "行数据");

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {// 7.关闭连接资源(注意顺序:后打开的先关闭)
            JdbcUtil.close(conn, stmt);

        }

    }


就光看看代码长度,是不是已经简化了好多呢?(必须滴)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值