自定义一个JdbcTemplate(增删改数据库中表记录)

需求:

  • 自定义一个JdbcTemplate模板,实现增删改数据库中表记录的功能
     1 package demo03;
     2 
     3 import utils.JDBC_DBCP_Utils;
     4 
     5 import javax.sql.DataSource;
     6 import java.sql.Connection;
     7 import java.sql.ParameterMetaData;
     8 import java.sql.PreparedStatement;
     9 import java.sql.SQLException;
    10 
    11 public class MyJDBCTemplate {
    12     //1. 需要传入数据源
    13     private DataSource dataSource;
    14 
    15     //构造方法
    16     public MyJDBCTemplate(DataSource dataSource) {
    17         this.dataSource = dataSource;
    18     }
    19 
    20     /**
    21      * 封装了JDBC操作数据库的步骤+元数据, 释放资源(使用者不需要关注释放资源了)
    22      * 进行增,删,修改
    23      *
    24      * @param sql    sql语句
    25      * @param params 参数
    26      * @return Ctrl+Alt+T
    27      */
    28     public int update(String sql, Object... params) {
    29         Connection connection = null;
    30         PreparedStatement preparedStatement = null;
    31         try {
    32             //0. 非空判断
    33             if (dataSource == null) throw new RuntimeException("dataSource must not null...");
    34 
    35             if (sql == null) throw new RuntimeException("sql must not null...");
    36 
    37             //1. 从dataSource 获得连接对象
    38             connection = dataSource.getConnection();
    39             //2. 创建预编译的sql语句对象 insert into user values (?,?,?,?)
    40             preparedStatement = connection.prepareStatement(sql);
    41 
    42             //3. 获得参数的元数据对象
    43             ParameterMetaData parameterMetaData = preparedStatement.getParameterMetaData();
    44             //4. 获得参数的个数
    45             int parameterCount = parameterMetaData.getParameterCount();
    46 
    47             //5. 给每一个?赋值
    48             for (int i = 0; i < parameterCount; i++) {
    49                 preparedStatement.setObject(i + 1, params[i]);
    50             }
    51 
    52             //6. 执行
    53             int i = preparedStatement.executeUpdate();
    54             return i;
    55         } catch (SQLException e) {
    56             e.printStackTrace();
    57         } finally {
    58             //释放资源
    59             JDBC_DBCP_Utils.release(null, preparedStatement, connection);
    60         }
    61         return -1;
    62     }
    63 }

     

posted @ 2019-06-16 21:55  optimistic&cheerful  阅读(846)  评论(0编辑  收藏  举报