• JDBC,数据库连接池,DBUtils,MYSQL批处理,MYSQL元数据


    JDBCUtils:

    import com.alibaba.druid.pool.DruidDataSourceFactory;
    
    import javax.sql.DataSource;
    import java.io.IOException;
    import java.io.InputStream;
    import java.sql.*;
    import java.util.Properties;
    
    public class JdbcUtil {
        private static DataSource dataSource; //数据库连接池
        static {
            Properties properties = new Properties();
            InputStream is = JdbcUtil.class.getClassLoader().getResourceAsStream("druid.properties");
            try {
                properties.load(is);
                is.close();
                dataSource = DruidDataSourceFactory.createDataSource(properties);
            }  catch (IOException ioException) {
                ioException.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        public static Connection getConnection() throws Exception {
            return dataSource.getConnection();
        }
        public static Connection getConnectionOld() throws IOException, ClassNotFoundException, SQLException {
            InputStream is=JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
            Properties properties = new Properties();
            properties.load(is);
            is.close();
    
            String driverClass=properties.getProperty("driverClass");
            String url=properties.getProperty("url");
            String user=properties.getProperty("user");
            String password=properties.getProperty("password");
    
            Class.forName(driverClass);
            Connection connection = DriverManager.getConnection(url, user, password);
            return connection;
    
        }
    
        public static void close(Connection connection){
           close(connection,null,null);
        }
    
        public static void close(Connection connection, Statement statement){
            close(connection,statement,null);
        }
    
        public static void close(Connection connection, Statement statement, ResultSet resultSet){
            if(resultSet!=null){
                try {
                    resultSet.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(statement!=null){
                try {
                    statement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    
    }

    druid.properties:

    driverClassName=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/jdbc?characterEncoding=UTF-8
    username=root
    password=123456
    
    #初始化容量
    initialSize = 3
    #最大激活数
    maxActive =100
    #最小发呆数
    minIdle =10

    CommonUtil:

    import java.io.IOException;
    import java.sql.*;
    import java.util.ArrayList;
    import java.util.List;
    
    public class CommonUtil {
        public static int update(Connection connection,String sql,Object...args) throws SQLException, IOException, ClassNotFoundException {
    
            PreparedStatement preparedStatement = null;
            preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i+1,args[i]);
            }
            return preparedStatement.executeUpdate();
    
    
    
        }
        public static void view(Connection connection,String sql,Object...args) throws SQLException, IOException, ClassNotFoundException {
            List<Customer> list = new ArrayList<>();
            PreparedStatement preparedStatement = null;
            ResultSet resultSet = null;
    
            preparedStatement = connection.prepareStatement(sql);
            //设置参数
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i+1,args[i]);
            }
    
            resultSet = preparedStatement.executeQuery();
            ResultSetMetaData resultSetMetaData =resultSet.getMetaData();
    
            //输出表头
            for (int i = 0; i < resultSetMetaData.getColumnCount(); i++) {
                System.out.print(resultSetMetaData.getColumnLabel(i+1)+"	");
            }
            System.out.println();
    
    
            while (resultSet.next()) {
                for (int i = 0; i < resultSetMetaData.getColumnCount(); i++) {
                    Object object = resultSet.getObject(resultSetMetaData.getColumnLabel(i + 1));
                    System.out.print(object+"	");
                }
                System.out.println();
            }
    
        }
    }

     

    JDBCDAO:

    import com.atguigu.day23.JdbcUtil;
    import org.apache.commons.dbutils.QueryRunner;
    import org.apache.commons.dbutils.handlers.BeanHandler;
    import org.apache.commons.dbutils.handlers.BeanListHandler;
    import org.apache.commons.dbutils.handlers.ScalarHandler;
    
    import java.io.IOException;
    import java.sql.Connection;
    import java.sql.SQLException;
    import java.util.List;
    
    public class JdbcDao<T> {
        private QueryRunner queryRunner = new QueryRunner();
        private Class<T> clazz;
    
        public JdbcDao(Class<T> clazz) {
            this.clazz = clazz;
        }
        public T getBean(String sql, Object... args) throws Exception {
            Connection connection = null;
            try {
                connection = JdbcUtil.getConnection();
                BeanHandler<T> beanHandler = new BeanHandler<T>(clazz);
                return queryRunner.query(connection, sql, beanHandler, args);
            } finally {
                JdbcUtil.close(connection);
            }
        }
    
        public List<T> getList(String sql, Object... args) throws Exception {
            Connection connection = null;
            try {
                connection = JdbcUtil.getConnection();
                BeanListHandler<T> beanListHandler = new BeanListHandler<T>(clazz);
                return queryRunner.query(connection, sql, beanListHandler, args);
            } finally {
                JdbcUtil.close(connection);
            }
        }
    
        public Object getValue(String sql, Object... args) throws Exception {
            Connection connection = null;
            try {
                connection = JdbcUtil.getConnection();
                ScalarHandler scalarHandler = new ScalarHandler();
                return queryRunner.query(connection, sql, scalarHandler, args);
            } finally {
                JdbcUtil.close(connection);
            }
        }
    
        public int update(String sql, Object... args) throws Exception {
            Connection connection = null;
            try {
                connection = JdbcUtil.getConnection();
                return queryRunner.update(connection, sql, args);
            } finally {
                JdbcUtil.close(connection);
            }
        }
    }

    查询测试:

     @Test
        public void test4(){
            JdbcDao<Customer> customerJdbcDao = new JdbcDao<>(Customer.class);
            try {
                Customer bean = customerJdbcDao.getBean("select * from customer where id =?",1);
                System.out.println("bean = " + bean);
    
                List<Customer> list = customerJdbcDao.getList("select * from customer where id<?", 4);
                System.out.println("list = " + list);
    
                Object value = customerJdbcDao.getValue("select avg(age) from customer");
                System.out.println("value = " + value);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    批处理:

      mysql 批处理是默认关闭的,所以需要加一个参数才打开mysql 数据库批处理,在url中添加:

    rewriteBatchedStatements=true
    例如: url=jdbc:mysql://127.0.0.1:3306/db5?characterEncoding=UTF-8&rewriteBatchedStatements=true

    package com.lagou.testbatch;
    
    import com.lagou.utils.DruidUtils;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    
    public class BatchInsert {
    
        //使用批处理 向表中添加 10000条数据
        public static void main(String[] args) throws SQLException {
    
            //1.获取连接
            Connection connection = DruidUtils.getConnection();
    
            //2.获取预处理对象
            PreparedStatement ps = connection.prepareStatement("insert into testBatch(uname) values(?)");
    
            //3.执行批量插入操作
            for (int i = 0; i < 10000 ; i++){
                ps.setString(1,"小强" + i);
    
                //将SQL添加到批处理列表
                ps.addBatch();
            }
            //添加时间戳 测试执行效率
            long start = System.currentTimeMillis();
    
            //4.统一执行 批量插入操作
            ps.executeBatch();
    
            long end = System.currentTimeMillis();
    
            System.out.println("插入10000条数据需要使用: " + (end - start) + " 毫秒!");
            //5.关闭连接
            DruidUtils.close(connection,ps);
        }
    
    }

    MySql元数据:

    除了表之外的数据都是元数据,可以分为三类:

    • 查询结果信息: UPDATE 或 DELETE语句 受影响的记录数。
    • 数据库和数据表的信息: 包含了数据库及数据表的结构信息。
    • MySQL服务器信息: 包含了数据库服务器的当前状态,版本号等。
    show status; 查看服务器的状态信息
    select version(); 获取mysql服务器的版本信息
    show columns from table_name; 显示表的字段信息等,和desc table_name一样
    show index from table_name; 显示数据表的详细索引信息,包括PRIMARY KEY(主键)

    JDBC中描述元数据的类:

    获取元数据对象的方法 getMetaData ():

    • connection 连接对象, 调用 getMetaData () 方法,获取的是DatabaseMetaData数据库元数据对象
    • PrepareStatement 预处理对象调用 getMetaData () , 获取的是ResultSetMetaData , 结果集元数据对象

    DatabaseMetaData的常用方法:

    ResultSetMetaData的常用方法:

    package com.lagou.testmetadata;
    
    import com.lagou.utils.DruidUtils;
    import org.junit.Test;
    
    import java.sql.*;
    
    public class TestMetaData {
    
        //1.获取数据库相关的元数据信息 使用DatabaseMetaData
        @Test
        public void testDataBaseMetaData() throws SQLException {
    
            //1.获取数据库连接对象 connection
            Connection connection = DruidUtils.getConnection();
    
            //2.获取代表数据库的 元数据对象 DatabaseMetaData
            DatabaseMetaData metaData = connection.getMetaData();
    
            //3.获取数据库相关的元数据信息
            String url = metaData.getURL();
            System.out.println("数据库URL: " + url);
    
            String userName = metaData.getUserName();
            System.out.println("当前用户: " + userName );
    
            String productName = metaData.getDatabaseProductName();
            System.out.println("数据库产品名: " + productName);
    
            String version = metaData.getDatabaseProductVersion();
            System.out.println("数据库版本: " + version);
    
            String driverName = metaData.getDriverName();
            System.out.println("驱动名称: " + driverName);
    
            //判断当前数据库是否只允许只读
            boolean b = metaData.isReadOnly();  //如果是 true 就表示 只读
            if(b){
                System.out.println("当前数据库只允许读操作!");
            }else{
                System.out.println("不是只读数据库");
            }
    
            connection.close();
        }
    
       //获取结果集中的元数据信息
        @Test
        public void testResultSetMetaData() throws SQLException {
    
            //1.获取连接
            Connection con = DruidUtils.getConnection();
    
            //2.获取预处理对象
            PreparedStatement ps = con.prepareStatement("select * from employee");
            ResultSet resultSet = ps.executeQuery();
    
            //3.获取结果集元素据对象
            ResultSetMetaData metaData = ps.getMetaData();
    
            //1.获取当前结果集 共有多少列
            int count = metaData.getColumnCount();
            System.out.println("当前结果集中共有: " + count + " 列");
    
            //2.获结果集中 列的名称 和 类型
            for (int i = 1; i <=  count; i++) {
                String columnName = metaData.getColumnName(i);
                System.out.println("列名: "+ columnName);
    
                String columnTypeName = metaData.getColumnTypeName(i);
                System.out.println("类型: " +columnTypeName);
            }
    
            //释放资源
            DruidUtils.close(con,ps,resultSet);
        }
    
    }
  • 相关阅读:
    博弈论专题(持续更新)
    数论专题(持续更新)
    树的遍历专题(持续更新)
    直线折线分割平面问题
    字典树模板 HDU1251
    差分数组——面对大数据的处理
    最短路——dijkstra算法
    并查集与最小生成树
    KMP的初步认识及题目分析
    Codeforces Round#636(Div.3) D题 差分数组
  • 原文地址:https://www.cnblogs.com/wanghzh/p/14810295.html
Copyright © 2020-2023  润新知