【小工具】mysql表导出csv的使用

导出DB库内所有表字段到不同sheet,生成csv文件

      • 小工具第二篇
  • 总结

小工具第二篇

平时工作中,我们需要将数据库内到表全部导出到文件中,目前市面上其他导出工具并不能支持导出到不同sheet页面上,类似于下图所示 db所有表的结构都导出来了

【小工具】mysql表导出csv的使用_第1张图片

代码如下(示例):

package com.shopee.bank.business.utility;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import org.apache.commons.lang.StringUtils;

import java.sql.*;
import java.util.*;
import java.util.stream.Collectors;

public class DBUtil {

    // JDBC driver name and database URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";

    static final String DBName="xxxxxx";

    // SIT3
    static final String DB_URL = "jdbc:mysql://xxxx:3306/"+DBName+"?useSSL=false";

    //  Database credentials -- 数据库名和密码自己修改
    static final String USER = "";
    static final String PASS = "";

    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try{
            //STEP 2: Register JDBC driver
            Class.forName("com.mysql.jdbc.Driver");

            //STEP 3: Open a connection
            System.out.println("Connecting to database...");
            conn = DriverManager.getConnection(DB_URL,USER,PASS);

            //STEP 4: Execute a query
            System.out.println("Creating statement...");
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT  TABLE_SCHEMA,TABLE_NAME, " +
                    "    TABLE_COMMENT  FROM " +
                    "    information_schema.`TABLES` " +
                    "WHERE " +
                    "    TABLE_SCHEMA = '"+DBName +"'";

            ResultSet rs = stmt.executeQuery(sql);

            //STEP 5: Extract data from result set
            Set<String> tables=new HashSet<>();
            while(rs.next()){
                //Retrieve by column name
                String tableName = rs.getString("TABLE_NAME");
                tables.add(tableName);
            }

            output(tables ,stmt);
            //STEP 6: Clean-up environment
            rs.close();
            stmt.close();
            conn.close();
        }catch(SQLException se){
            //Handle errors for JDBC
            se.printStackTrace();
        }catch(Exception e){
            //Handle errors for Class.forName
            e.printStackTrace();
        }finally{
            //finally block used to close resources
            try{
                if(stmt!=null)
                    stmt.close();
            }catch(SQLException se2){
            }// nothing we can do
            try{
                if(conn!=null)
                    conn.close();
            }catch(SQLException se){
                se.printStackTrace();
            }//end finally try
        }//end try
        System.out.println("Goodbye!");
    }

    public static void output(Set<String> tables,Statement stmt) throws SQLException {

        String sql;
        sql  =  "SELECT " +
                "COLUMN_NAME,DATA_TYPE,IS_NULLABLE,COLUMN_DEFAULT ,COLUMN_COMMENT " +
                "FROM   INFORMATION_SCHEMA.COLUMNS " +
                "where  table_schema = "+"'"+DBName+ "'"+ "AND  table_name = ";

        String[] headers = {"No.", "Column Name","Data Type", "Not Null", "Default", "Comments"};
        List<String> row = CollUtil.newArrayList(headers);
        ExcelWriter writer = ExcelUtil.getWriter("/Users/kaiyi.wang/Desktop/sgdb.csv");

        for (String table : tables) {
            StringBuilder sb =new StringBuilder(sql);
            sb.append("'").append(table).append("'");
            ResultSet rs = stmt.executeQuery(sb.toString());

            Collection<List<String>> coll = new ArrayList();
            coll.add(row);

            // 每行序列号
            int index=1;
            while(rs.next()){
                List<String> rows=new ArrayList<>();
                rows.add(index+++"");
                // 处理每行数据
                for (int i = 1; i <= 5; i++) {
                    String rowValue = rs.getString(i);
                    rowValue=StringUtils.isEmpty(rowValue)?"":rowValue;
                    rows.add(rowValue);
                }
                coll.add(rows);
            }
            // 设置sheet
            writer.setSheet(table);
            writer.write(coll);
            writer.flush();
        }
    }
}


总结

以上就是今天要讲的内容,简单介绍了mysql导出csv的使用

你可能感兴趣的:(Mysql,mysql,数据库,sql,导出)