当前位置:网站首页>Detailed use of dbutils # yyds dry goods inventory #

Detailed use of dbutils # yyds dry goods inventory #

2022-07-06 02:48:00 Liang Yunliang

DBUtils

brief introduction

DBUtils yes Java Database operation utility in programming , Small, simple and practical .DBUtils Encapsulates the JDBC The operation of , To simplify the JDBC operation , Can reduce the 60% Code above .

DBUtils Introduction to three core functions

  • QueryRunner: Core classes provide access to sql Statement operation API
    • QueryRunner(DataSourcr ds): Provide data sources ( Connection pool ),DbUtils Bottom layer automatic maintenance connection connection
    • update(String sql,Obj…params): Perform an update operation
    • query(String sql,ResultSetHandler<T>rsh,Object…panrams): Perform query operation
  • ResultSetHandler: Result set processing class , Used for definition select After the operation , How to encapsulate result sets
    • ArrayHandler: Put the first row of data in the query result set into an array . Suitable for 1 Bar record .
    • ArrayListHandler: Put each row of data in the query result into an array , Then put the array into the collection List in . It is suitable for taking multiple records .
    • BeanHandler: Encapsulate the first row of data in the result set into a corresponding JavaBean In the example
    • BeanListHandler: Encapsulate each row of data in the result set into a corresponding JavaBean In the example , Then store these objects in List in .
    • MapHandler: Encapsulate the first row of data in the result set into a Map in ,key Is the column name ,value Is the corresponding value .
    • MapListHandler: Save each row of the query result into a map in , Key is column name , The value is the value of each column ; And then map Deposit in list in
    • ColumnListHandler: Store the data of a column in the result set in List in .
    • KeyedHandler(name): Encapsulate each row of data in the result set into a Map in (List<Map>), And then put these map Save one more map in , Its key For the specified column .
    • ScalarHandler: Put a column in the first row of the result set into an object .// a key
  • DBUtils: Tool class , Defines methods for closing resources and transactions .

Example : use Druid and dbutils Realize to Dept Of CRUD

  • First step :Dept.java:<a rel=“nofollow” href=“ https://blog.csdn.net/lianghecai52171314/article/details/101469279”>Dept Source code </a>

  • The second step : New projects , Join in Maven rely on :

    <dependency>
      <groupId>commons-dbutils</groupId>
      <artifactId>commons-dbutils</artifactId>
      <version>1.7</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.17</version>
    </dependency>
    
           
    • 1.
    • 2.
    • 3.
    • 4.
    • 5.
    • 6.
    • 7.
    • 8.
    • 9.
    • 10.
  • The second step : stay resources Create under directory mysql.properties, The code is as follows :

    driverClassName=com.mysql.cj.jdbc.Driver
    url=jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC&user=root&password=&useUnicode=true&characterEncoding=UTF8&autoReconnect=true&failOverReadOnly=false
    username=root
    password=root
    
    
    filters=stat
    initialSize=2
    maxActive=300
    maxWait=60000
    timeBetweenEvictionRunsMillis=60000
    minEvictableIdleTimeMillis=300000
    validationQuery=SELECT 1
    testWhileIdle=true
    testOnBorrow=false
    testOnReturn=false
    poolPreparedStatements=false
    maxPoolPreparedStatementPerConnectionSize=200
    
           
    • 1.
    • 2.
    • 3.
    • 4.
    • 5.
    • 6.
    • 7.
    • 8.
    • 9.
    • 10.
    • 11.
    • 12.
    • 13.
    • 14.
    • 15.
    • 16.
    • 17.
    • 18.
  • The third step : Create a database connection tool class :

    public class DBUtil {
        private static final ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
        private static DataSource dataSource = null;
    
        private DBUtil() {
        }
    
        static {    // Profile loading , Only once 
            try (InputStream is = DBUtil.class.getResourceAsStream("/mysql.properties");) {
                Properties properties = new Properties();
                properties.load(is);
                dataSource = DruidDataSourceFactory.createDataSource(properties);
            } catch (Exception e1) {
                throw new RuntimeException(" Exception reading configuration file ", e1);
            }
        }
    
        public static Connection getConnection() {    // Get the connection 
            Connection conn = null;
            try {
                conn = threadLocal.get();   // Get from current thread  conn
                if (conn == null || conn.isClosed()) {
                    conn = dataSource.getConnection();
                    threadLocal.set(conn);
                }
            } catch (Exception e) {
                throw new RuntimeException(" Connection database exception ", e);
            }
            return conn;
        }
    
        public static QueryRunner getQueryRunner() {
            return new QueryRunner(dataSource);
        }
    
        public static void release(Connection conn) {
            try { //  This form is recommended to release resources , because finally The inside will be released 
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    
           
    • 1.
    • 2.
    • 3.
    • 4.
    • 5.
    • 6.
    • 7.
    • 8.
    • 9.
    • 10.
    • 11.
    • 12.
    • 13.
    • 14.
    • 15.
    • 16.
    • 17.
    • 18.
    • 19.
    • 20.
    • 21.
    • 22.
    • 23.
    • 24.
    • 25.
    • 26.
    • 27.
    • 28.
    • 29.
    • 30.
    • 31.
    • 32.
    • 33.
    • 34.
    • 35.
    • 36.
    • 37.
    • 38.
    • 39.
    • 40.
    • 41.
    • 42.
    • 43.
    • 44.
    • 45.
  • Step four : Test transactions

    public static void main(String[] args) {
        Connection conn = getConnection();
        try {
            conn.setAutoCommit(false); //  Set transaction commit to manual 
            String sql = "insert into tb_dept (dname,loc) values(?,?)";
            QueryRunner queryRunner = getQueryRunner();
            queryRunner.update(conn, sql, "aa", "aaaaa");
            System.out.println(3 / 0);
            queryRunner.update(sql, "bb", "bbbbbbbbbb");
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {
            release(conn);
        }
    }
    
           
    • 1.
    • 2.
    • 3.
    • 4.
    • 5.
    • 6.
    • 7.
    • 8.
    • 9.
    • 10.
    • 11.
    • 12.
    • 13.
    • 14.
    • 15.
    • 16.
    • 17.
    • 18.
    • 19.
    • 20.
    • 21.
  • Step five :DeptDaoImpl.java

    public class DeptDaoImpl {
        private QueryRunner queryRunner = DBUtil.getQueryRunner();
    
        public int insertDept(Dept dept) throws SQLException {
            String sql = "insert into tb_dept (deptno, dname, loc) values (?, ?, ?)";
            return queryRunner.update(sql, dept.getDeptno(), dept.getDname(), dept.getLoc());
        }
    
        public int batchInsertDept(List<Dept> deptList) throws SQLException {
            Object[][] params = new Object[deptList.size()][3];
    
            for (int i = 0; i < params.length; i++) {
                Dept dept = deptList.get(i);
                params[i][0] = dept.getDeptno();
                params[i][1] = dept.getDname();
                params[i][2] = dept.getLoc();
            }
    
            StringBuilder wenHao = new StringBuilder();
            for (int i = 0; i < params[0].length; i++) {
                wenHao.append("?,");
            }
            String sql = "insert into tb_dept values(" + wenHao.deleteCharAt(wenHao.length() - 1) + ")";
    
            queryRunner.batch(sql, params);
            return 1;  //  If you don't throw an exception , Just go back to 1, Indicates that the deletion was successful 
        }
    
        public int deleteDeptByDeptno(Byte deptno) throws SQLException {
            String sql = "delete from tb_dept where deptno = ?";
            return queryRunner.update(sql, deptno);
        }
    
        public int deleteDeptByCondition(Dept dept) throws SQLException {
            List<Object> paramValueList = new ArrayList<>();
            StringBuffer paramBuf = new StringBuffer("1=1 ");
    
            if (dept.getDeptno() != null) {
                paramBuf.append("and deptno= ? ");
                paramValueList.add(dept.getDeptno());
            }
            if (dept.getDname() != null) {
                paramBuf.append("and dname= ? ");
                paramValueList.add(dept.getDname());
            }
            if (dept.getLoc() != null) {
                paramBuf.append("and loc= ? ");
                paramValueList.add(dept.getLoc());
            }
    
            String sql = "delete from tb_dept where " + paramBuf.substring(0, paramBuf.length() - 3);
            return queryRunner.update(sql, paramValueList.toArray());
        }
    
        public int batchDeleteDeptByDeptnos(String deptnos) throws SQLException {
            String[] split = deptnos.split(",");
            Object[][] params = new Object[1][];
    
            StringBuilder wenHao = new StringBuilder();
            for (int i = 0; i < split.length; i++) {
                wenHao.append("?,");
            }
            params[0] = split;
    
            String sql = "delete from tb_dept where deptno in (" + wenHao.deleteCharAt(wenHao.length() - 1) + ")";
    
            queryRunner.batch(sql, params);
            return 1;  //  If you don't throw an exception , Just go back to 1, Indicates that the deletion was successful 
        }
    
        public int updateDept(Dept dept) throws SQLException {
            String sql = "update tb_dept set dname= ? ,loc= ? where deptno = ?";
            return queryRunner.update(sql, dept.getDname(), dept.getLoc(), dept.getDeptno());
        }
    
        public long selectCount() throws SQLException {
            String sql = "select count(*) from tb_dept";
            // ScalarHandler: Put a column in the first row of the query result into an object ; Pinpoint to a value 
            Long query = queryRunner.query(sql, new ScalarHandler<Long>());
            return query.intValue();
        }
    
        public long selectCountByCondition(Dept dept) throws SQLException {
            List<Object> paramValueList = new ArrayList<>();
            StringBuffer paramBuf = new StringBuffer("1=1 ");
    
            if (dept.getDeptno() != null) {
                paramBuf.append("and deptno= ? ");
                paramValueList.add(dept.getDeptno());
            }
            if (dept.getDname() != null) {
                paramBuf.append("and dname= ? ");
                paramValueList.add(dept.getDname());
            }
            if (dept.getLoc() != null) {
                paramBuf.append("and loc= ? ");
                paramValueList.add(dept.getLoc());
            }
    
            String sql = "select count(*) from tb_dept where " + paramBuf.substring(0, paramBuf.length() - 3);
            Long query = queryRunner.query(sql, new ScalarHandler<Long>(), paramValueList.toArray());
            return query.intValue();
        }
    
        public Dept selectDeptByDeptno(Byte deptno) throws SQLException {
            String sql = "select deptno as deptno, dname as dname, loc as loc from tb_dept where deptno = ?";
            return queryRunner.query(sql, new BeanHandler<>(Dept.class), deptno);
        }
    
        public List<Dept> selectAllDept() throws SQLException {
            String sql = "select deptno as deptno, dname as dname, loc as loc from tb_dept";
            return queryRunner.query(sql, new BeanListHandler<>(Dept.class));
        }
    
        public List<Dept> selectDeptByCondition(Dept dept) throws SQLException {
            List<Object> paramValueList = new ArrayList<>();
            StringBuffer paramBuf = new StringBuffer("1=1 ");
    
            if (dept.getDeptno() != null) {
                paramBuf.append("and deptno= ? ");
                paramValueList.add(dept.getDeptno());
            }
            if (dept.getDname() != null) {
                paramBuf.append("and dname= ? ");
                paramValueList.add(dept.getDname());
            }
            if (dept.getLoc() != null) {
                paramBuf.append("and loc= ? ");
                paramValueList.add(dept.getLoc());
            }
    
            String sql = "select deptno as deptno, dname as dname, loc as loc from tb_dept where " + paramBuf.substring(0, paramBuf.length() - 3);
            return queryRunner.query(sql, new BeanListHandler<>(Dept.class), paramValueList.toArray());
        }
    
        public List<Dept> selectDeptWithPagination(int page, int rows) throws SQLException {
            String sql = "select deptno as deptno, dname as dname, loc as loc from tb_dept limit ?, ?";
            return queryRunner.query(sql, new BeanListHandler<>(Dept.class), (page - 1) * rows, rows);
        }
    
        public List<Dept> selectDeptWithPaginationByCondition(int page, int rows, Dept dept) throws SQLException {
            List<Object> paramValueList = new ArrayList<>();
            StringBuffer paramBuf = new StringBuffer("1=1 ");
    
            if (dept.getDeptno() != null) {
                paramBuf.append("and deptno= ? ");
                paramValueList.add(dept.getDeptno());
            }
            if (dept.getDname() != null) {
                paramBuf.append("and dname= ? ");
                paramValueList.add(dept.getDname());
            }
            if (dept.getLoc() != null) {
                paramBuf.append("and loc= ? ");
                paramValueList.add(dept.getLoc());
            }
    
            String sql = "select deptno as deptno, dname as dname, loc as loc from tb_dept where " + paramBuf.substring(0, paramBuf.length() - 3) + " limit ?, ?";
    
            paramValueList.add((page - 1) * rows);
            paramValueList.add(rows);
            return queryRunner.query(sql, new BeanListHandler<>(Dept.class), paramValueList.toArray());
        }
    }
    
           
    • 1.
    • 2.
    • 3.
    • 4.
    • 5.
    • 6.
    • 7.
    • 8.
    • 9.
    • 10.
    • 11.
    • 12.
    • 13.
    • 14.
    • 15.
    • 16.
    • 17.
    • 18.
    • 19.
    • 20.
    • 21.
    • 22.
    • 23.
    • 24.
    • 25.
    • 26.
    • 27.
    • 28.
    • 29.
    • 30.
    • 31.
    • 32.
    • 33.
    • 34.
    • 35.
    • 36.
    • 37.
    • 38.
    • 39.
    • 40.
    • 41.
    • 42.
    • 43.
    • 44.
    • 45.
    • 46.
    • 47.
    • 48.
    • 49.
    • 50.
    • 51.
    • 52.
    • 53.
    • 54.
    • 55.
    • 56.
    • 57.
    • 58.
    • 59.
    • 60.
    • 61.
    • 62.
    • 63.
    • 64.
    • 65.
    • 66.
    • 67.
    • 68.
    • 69.
    • 70.
    • 71.
    • 72.
    • 73.
    • 74.
    • 75.
    • 76.
    • 77.
    • 78.
    • 79.
    • 80.
    • 81.
    • 82.
    • 83.
    • 84.
    • 85.
    • 86.
    • 87.
    • 88.
    • 89.
    • 90.
    • 91.
    • 92.
    • 93.
    • 94.
    • 95.
    • 96.
    • 97.
    • 98.
    • 99.
    • 100.
    • 101.
    • 102.
    • 103.
    • 104.
    • 105.
    • 106.
    • 107.
    • 108.
    • 109.
    • 110.
    • 111.
    • 112.
    • 113.
    • 114.
    • 115.
    • 116.
    • 117.
    • 118.
    • 119.
    • 120.
    • 121.
    • 122.
    • 123.
    • 124.
    • 125.
    • 126.
    • 127.
    • 128.
    • 129.
    • 130.
    • 131.
    • 132.
    • 133.
    • 134.
    • 135.
    • 136.
    • 137.
    • 138.
    • 139.
    • 140.
    • 141.
    • 142.
    • 143.
    • 144.
    • 145.
    • 146.
    • 147.
    • 148.
    • 149.
    • 150.
    • 151.
    • 152.
    • 153.
    • 154.
    • 155.
    • 156.
    • 157.
    • 158.
    • 159.
    • 160.
    • 161.
    • 162.
    • 163.
    • 164.

dynamic SQL And static SQL

SQL Statements can be divided into static statements from the perspective of compilation and operation SQL and dynamic SQL, So-called SQL The dynamic and static state of , Refer to SQL When statements are compiled and executed .

These two kinds of SQL In the way of use 、 Operation mechanism and performance have their own characteristics :

  • static state SQL: static state SQL Statements are generally used in embedded systems SQL Application , Before the program runs ,SQL Statements must be certain when programming , for example SQL The column and table names involved in the statement must exist . static state SQL Statement is compiled before the application runs , The compiled results are stored in the database . Then the program runs , The database will directly execute the compiled SQL sentence , Reduce runtime overhead .
  • dynamic SQL: dynamic SQL Statements are compiled and executed while the application is running , for example , Use DB2 Interactive tools for CLP When accessing the database , User entered SQL The statement is indeterminate , therefore SQL Statements can only be compiled dynamically . dynamic SQL More applications , common CLI and JDBC Applications use dynamic SQL.

static state sql The access path of is determined before running , And dynamic sql The access path is dynamically generated at run time .

Be careful : stay SQL If some parameters are not determined , Such as "select * from t1 where c1>? and c2<?", This statement is static SQL, Not dynamic SQL, Although the value of individual parameters is not known , But the whole SQL The structure of has been determined , The database can be compiled , In the execution phase, you only need to add the values of individual parameters .

原网站

版权声明
本文为[Liang Yunliang]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202132353286568.html