获得mysql数据库信息 (字段名字段类型字段注释)工具类

Posted 我没有出家

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获得mysql数据库信息 (字段名字段类型字段注释)工具类相关的知识,希望对你有一定的参考价值。

public class DbInfoUtil {

    /**
     * 根据数据库的连接参数,获取指定表的基本信息:字段名、字段类型、字段注释
     * @param driver 数据库连接驱动
     * @param url 数据库连接url
     * @param user    数据库登陆用户名
     * @param pwd 数据库登陆密码
     * @param table    表名
     * @return Map集合
     */
    public static List<Map<String,Object>> getTableInfo(String driver,String url,String user,String pwd,String table){
        List<Map<String,Object>> result = new ArrayList<>();

        Connection conn = null;
        DatabaseMetaData dbmd = null;

        try {
            List<String> breakmark=new ArrayList<>();
            conn = getConnections(driver,url,user,pwd);

            dbmd = conn.getMetaData();
            ResultSet resultSet = dbmd.getTables(null, "%", table, new String[] { "TABLE" });

            while (resultSet.next()) {
                String tableName=resultSet.getString("TABLE_NAME");

                if(tableName.equals(table)){
                    ResultSet rs = conn.getMetaData().getColumns(null, getSchema(conn),tableName.toUpperCase(), "%");

                    while(rs.next()){

                        //System.out.println("字段名:"+rs.getString("COLUMN_NAME")+"--字段注释:"+rs.getString("REMARKS")+"--字段数据类型:"+rs.getString("TYPE_NAME"));
                        Map map = new HashMap();
                        String colName = rs.getString("COLUMN_NAME");
                        if(breakmark.contains(colName)){
                            break;
                        }
                        map.put("code", colName);
                        breakmark.add(colName);
                        String remarks = rs.getString("REMARKS");
                        if(remarks == null || remarks.equals("")){
                            remarks = colName;
                        }
                        map.put("name",remarks);

                        String dbType = rs.getString("TYPE_NAME");
                        map.put("dbType",dbType);

                        map.put("valueType", changeDbType(dbType));
                        result.add(map);
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    private static String changeDbType(String dbType) {
        dbType = dbType.toUpperCase();
        switch(dbType){
            case "VARCHAR":
            case "VARCHAR2":
            case "CHAR":
                return "1";
            case "NUMBER":
            case "DECIMAL":
                return "4";
            case "INT":
            case "SMALLINT":
            case "INTEGER":
                return "2";
            case "BIGINT":
                return "6";
            case "DATETIME":
            case "TIMESTAMP":
            case "DATE":
                return "7";
            default:
                return "1";
        }
    }

    //获取连接
    private static Connection getConnections(String driver,String url,String user,String pwd) throws Exception {
        Connection conn = null;
        try {
            Properties props = new Properties();
            props.put("remarksReporting", "true");
            props.put("user", user);
            props.put("password", pwd);
            Class.forName(driver);
            conn = DriverManager.getConnection(url, props);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return conn;
    }

    //其他数据库不需要这个方法 oracle和db2需要
    private static String getSchema(Connection conn) throws Exception {
        String schema;
        schema = conn.getMetaData().getUserName();
        if ((schema == null) || (schema.length() == 0)) {
            throw new Exception("ORACLE数据库模式不允许为空");
        }
        return schema.toUpperCase().toString();

    }

    public static void main(String[] args) {

        //这里是Oracle连接方法

        String driver = "oracle.jdbc.driver.OracleDriver";
        String url = "jdbc:oracle:thin:@192.168.12.44:1521:orcl";
        String user = "bdc";
        String pwd = "bdc123";
        String table = "FZ_USER_T";

        //mysql
        /*
        String driver = "com.mysql.jdbc.Driver";
        String user = "root";
        String pwd = "123456";
        String url = "jdbc:mysql://localhost/onlinexam"
                + "?useUnicode=true&characterEncoding=UTF-8";
        String table = "oe_student";
        */

        List list = getTableInfo(driver,url,user,pwd,table);
        System.out.println(list);
    }

}

 

***************写excle*********************

public class BigDataExcelOutWriteCopy {
    public static String driver="com.mysql.jdbc.Driver";

    public static String url = "jdbc:mysql://192.168.33.111:3306/xie20210222?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8";
    public static    String username = "root";
    public static    String password = "root";
    /**
     * 数据库连接操作
     * 
     * @throws Exception
     */
    public static Connection getConnection() throws Exception {

        // 获取数据库连接
        Connection conn = DriverManager.getConnection(url, username, password);
        return conn;
    }
 
    /**
     * 
     * @Title: WriteExcel
     * @Description: 执行导出Excel操作
     * @param
     * @return boolean
     * @throws
     */
    public boolean WriteExcel(boolean isClose,String tableName) {
        List<Map<String,Object>> list=DbInfoUtil.getTableInfo(driver,url,username,password,tableName);
        String excelFile = "D:/xe/zcj/"+tableName+".xlsx";
        // 内存中只创建100个对象,写临时文件,当超过100条,就将内存中不用的对象释放。
        SXSSFWorkbook wb = new SXSSFWorkbook(100);
        Sheet sheet = null; // 工作表对象
        Row nRow = null; // 行对象
        Cell nCell = null; // 列对象
 
        try {
 
            Connection conn = getConnection();
            Statement stmt = conn.createStatement();


            String sql="SELECT * from "+tableName+" limit 100";


            ResultSet rs = stmt.executeQuery(sql); // 获取u_id_number结果
            ResultSetMetaData rsmd = rs.getMetaData(); // 获取执行结果的结构(rs.getMetaData().getTableName(1))就可以返回表名,rs.getMetaData().getColumnCount())
 
            long startTime = System.currentTimeMillis();
            System.out.println("开始执行时间 : " + startTime / 1000 + "m");
            int rowNo = 0; // 总行号
            int pageRowNo = 0; // 页行号
 
            while (rs.next()) {
                // 打印1000000条后切换到下个工作表,可根据需要自行拓展,2百万,3百万...数据一样操作,只要不超过1048576就可以
                if (rowNo % 1000000 == 0) {
                    System.out.println("当前sheet页为:" + rowNo / 1000000 );
                    sheet = wb.createSheet("我的第" + (rowNo / 1000000 + 1) + "个工作簿");// 建立新的sheet对象
                    sheet = wb.getSheetAt(rowNo / 1000000); // 动态指定当前的工作表
                    pageRowNo = 1; // 每当新建了工作表就将当前工作表的行号重置为1
                    
                    //定义表头
                    nRow = sheet.createRow(0);

                    for(int k=0;k<list.size();k++){
                        Cell cel = nRow.createCell(k);
                        String value=list.get(k).get("name").toString();
                        cel.setCellValue(value);
                    }

                }
                rowNo++;
                nRow = sheet.createRow(pageRowNo++); // 新建行对象
 
                // 打印每行,每行有6列数据 rsmd.getColumnCount()==6 --- 列属性的个数
                for (int i = 0; i < rsmd.getColumnCount(); i++) {
                    nCell = nRow.createCell(i);
                    nCell.setCellValue(rs.getString(i + 1));
                }
 
                if (rowNo % 10000 == 0) {
                    System.out.println("row no: " + rowNo);
                }
            }
 
            long finishedTime = System.currentTimeMillis(); // 处理完成时间
            System.out.println("数据读取完成耗时 : " + (finishedTime - startTime) / 1000 + "m");
            
            FileOutputStream fOut = new FileOutputStream(excelFile);//将数据写入Excel
            wb.write(fOut);
            fOut.flush(); // 刷新缓冲区
            fOut.close();
 
            long stopTime = System.currentTimeMillis(); // 写文件时间
            System.out.println("数据写入Excel表格中耗时 : " + (stopTime - startTime) / 1000 + "m");
 
            if (isClose) {
                this.close(rs, stmt, conn);
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
 
    // 执行关闭流的操作
    private void close(ResultSet rs, Statement stmt, Connection conn)throws SQLException {
        rs.close();
        stmt.close();
        conn.close();
    }
    //测试方法
    public static void main(String[] args) throws Exception {
        BigDataExcelOutWriteCopy bdeo = new BigDataExcelOutWriteCopy();
        Connection conn = getConnection();
        Statement stmt = conn.createStatement();

        //    符合条件的数据表名
        String sql="select table_name from information_schema.tables where TABLE_SCHEMA = \'库名\' and table_name like \'zcj_%\'\\n" +
                " and table_rows !=0 order by table_rows desc;";


        ResultSet rs = stmt.executeQuery(sql); // 获取u_id_number结果
        while (rs.next()){
            String tableName = rs.getString(1);
            bdeo.WriteExcel(true,tableName);
        }


    }
}

 

以上是关于获得mysql数据库信息 (字段名字段类型字段注释)工具类的主要内容,如果未能解决你的问题,请参考以下文章

Mysql中用SQL增加删除字段,修改字段名字段类型注释,调整字段顺序总结

MySQL 查询数据库中某个表的所有字段名字段类型以及注释

MySQL数据库修改字段名字段类型字段长度

MySQL修改字段名字段类型

Mysql02

Mysql03