mysql获取建表语句

package com.zd.db;


import lombok.extern.slf4j.Slf4j;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class JdbcUtil {
    /**
     * 获取字段相关类:
     * 使用完记得关闭连接
     */
    public static ResultSetMetaData getResultSetMetaData(String tableName) {
        PreparedStatement preparedStatement = null;
        ResultSetMetaData resultSetMetaData = null;
        Connection connection = getConnection();
        try {
            preparedStatement = connection.prepareStatement("select * from " + tableName + " where 1=2");
            resultSetMetaData = preparedStatement.executeQuery().getMetaData();
        } catch (Exception e) {
            log.error("数据库连接异常", e);
        } finally {
            closePreparedStatement(preparedStatement);
            closeConnection(connection);
        }
        return resultSetMetaData;
    }


    /**
     * 创建表的新增记录触发器语句:
     * 使用完记得关闭连接
     */
    public static String getInsertTriggerSql(String tableName) {
        PreparedStatement preparedStatement = null;
        ResultSetMetaData resultSetMetaData = null;
        Connection connection = getConnection();
        String triggerColumns = "";
        String triggerOldValues = "";
        String triggerSql = "";
        try {
            preparedStatement = connection.prepareStatement("select * from " + tableName + " where 1=2");
            resultSetMetaData = preparedStatement.executeQuery().getMetaData();

            int columnCount = resultSetMetaData.getColumnCount();
            //System.out.println(tableName + "表中字段个数为:" + columnCount);

            for (int i = 1; i <= columnCount; i++) {
                String columnName = resultSetMetaData.getColumnName(i);
                triggerColumns += columnName + ",";
                triggerOldValues += "NEW." + columnName + ",";
            }

            triggerColumns = triggerColumns.substring(0, triggerColumns.length() - 1);
            triggerOldValues = triggerOldValues.substring(0, triggerOldValues.length() - 1);

            triggerSql = "create trigger " + tableName + "_bak " + "after insert on " + tableName + " for each row"
                    + " begin"
                    + " insert into " + tableName + "_history (" + triggerColumns + ") values (" + triggerOldValues + ");"
                    + " end";
        } catch (Exception e) {
            log.error("数据库连接异常", e);
        } finally {
            closePreparedStatement(preparedStatement);
            closeConnection(connection);
        }
        return triggerSql;
    }


    /**
     * 获取当前数据库下的所有表名称
     */
    public static List<String> getAllTableName() {
        List<String> tables = new ArrayList();
        Connection connection = getConnection();
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            statement = connection.createStatement();
            resultSet = statement.executeQuery("SHOW TABLES ");
            while (resultSet.next()) {
                String tableName = resultSet.getString(1);
                tables.add(tableName);
            }
        } catch (SQLException e) {
            log.error("数据库连接异常", e);
        } finally {
            closeResultSet(resultSet);
            closeStatement(statement);
            closeConnection(connection);
        }


        return tables;
    }


    /**
     * 获得某表的建表语句
     */
    public static String getCreateTableDDL(String tableName) {
        Connection connection = getConnection();
        Statement statement = null;
        ResultSet resultSet = null;
        String createDDLSql = null;
        try {
            statement = connection.createStatement();
            resultSet = statement.executeQuery("SHOW CREATE TABLE " + tableName);
            if (resultSet != null && resultSet.next()) {
                createDDLSql = resultSet.getString(2);
            }
        } catch (SQLException e) {
            log.error("数据库连接异常", e);
        } finally {
            closeResultSet(resultSet);
            closeStatement(statement);
            closeConnection(connection);
        }
        return createDDLSql;
    }

    public static String getCreateTableHistoryDDL(String sourceCreateTableDDL, String sourceTableName, String targetTableName) {
        return sourceCreateTableDDL.replaceFirst(sourceTableName, targetTableName);
    }

    public static String getAlterColumnCreateTableDDl(String sourceCreateTableDDL, String addColumnDefine) {
        return null;
    }

    public static String getAddColumnCreateTableDDl(String sourceCreateTableDDL, String addColumnDefine) {
        StringBuilder sb = new StringBuilder();
        sb.append(sourceCreateTableDDL).insert(sourceCreateTableDDL.indexOf("(")+1, addColumnDefine);

        return sb.toString();
    }

    /**
     * 获得某表的注释
     */
    public static String getTableCommnet(String tableName) {
        String creatDDLSql = getCreateTableDDL(tableName);
        String comment = null;
        int index = creatDDLSql.indexOf("COMMENT='");
        if (index < 0) {
            return "";
        }
        comment = creatDDLSql.substring(index + 9);
        comment = comment.substring(0, comment.length() - 1);
        return comment;
    }


    /**
     * 获取表中字段的所有注释
     */
    public static List<String> getColumnComments(String tableName) {
        //与数据库的连接
        Connection connection = getConnection();
        PreparedStatement preparedStatement = null;
        String tableSql = "select * from " + tableName;
        //列名注释集合
        List<String> columnComments = new ArrayList<>();
        ResultSet resultSet = null;
        try {
            preparedStatement = connection.prepareStatement(tableSql);
            resultSet = preparedStatement.executeQuery("show full columns from " + tableName);
            while (resultSet.next()) {
                columnComments.add(resultSet.getString("Comment"));
            }
        } catch (SQLException e) {
            log.error("数据库连接异常", e);
        } finally {
            closeResultSet(resultSet);
            closeStatement(preparedStatement);
            closeConnection(connection);
        }
        return columnComments;
    }


    /**
     * 获取数据连接
     */
    public static Connection getConnection() {
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/testdb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true", "root", "root");
        } catch (Exception e) {
            log.error("get connection failure", e);
        }
        return connection;
    }

    /**
     * 关闭数据库连接
     */
    public static void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                log.error("close connection failure", e);
            }
        }
    }

    public static void closePreparedStatement(PreparedStatement preparedStatement) {
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                log.error("close preparedStatement failure ", e);
            }
        }
    }

    public static void closeResultSet(ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                log.error("close resultSet failure ", e);
            }
        }
    }

    public static void closeStatement(Statement statement) {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                log.error("close statement failure ", e);
            }
        }
    }


    public static void main(String[] args) throws Exception{
        //System.out.println("获取所有数据库的表名" + getAllTableName());

        String tableName = "orders";
        String createTableDDL = getCreateTableDDL(tableName);
        System.out.println("获取建表语句:" + createTableDDL);

        String createTableHistoryDDL = getCreateTableHistoryDDL(createTableDDL, tableName, tableName + "_history");
        System.out.println("获取创建history表语句:" + createTableHistoryDDL);

        String addColumnCreateTableDDl = getAddColumnCreateTableDDl(createTableHistoryDDL.replaceFirst("AUTO_INCREMENT", "").replace("PRIMARY KEY","KEY `idx_key`"), "`rowId` BIGINT(20) NOT NULL AUTO_INCREMENT PRIMARY KEY,");
        System.out.println("新增字段创建表ddl:" + addColumnCreateTableDDl);

        String insertTriggerSql = getInsertTriggerSql(tableName);
        System.out.println("获取表的insert触发器:" + insertTriggerSql);

        //System.out.println("获取表的备注:" + getTableCommnet(tableName));


        /*ResultSetMetaData resultSetMetaData = getResultSetMetaData(tableName);
        int columnCount = resultSetMetaData.getColumnCount();
        System.out.println(tableName + "表中字段个数为:" + columnCount);

        System.out.println("打印字段信息:");
        List<String> columnComments = getColumnComments(tableName);


        for (int i = 1; i <= columnCount; i++) {
            String columnClassName = resultSetMetaData.getColumnClassName(i);
            System.out.print("java类型:" + columnClassName);

            String columnTypeName = resultSetMetaData.getColumnTypeName(i).toLowerCase();
            System.out.print("  数据库类型:" + columnTypeName);

            String columnName = resultSetMetaData.getColumnName(i);
            System.out.print("  字段名称:" + columnName);

            int columnDisplaySize = resultSetMetaData.getColumnDisplaySize(i);
            System.out.print("  字段长度:" + columnDisplaySize);

            System.out.print(" notNull:" + (resultSetMetaData.isNullable(i) == 1 ? false : true));

            String columnComment = columnComments.get(i - 1);
            System.out.println(" 注释为:" + columnComment);
        }*/



    }

}


获取建表语句:CREATE TABLE `orders` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ordertime` varchar(255) DEFAULT NULL,
  `total` double(5,2) DEFAULT NULL,
  `uid` int(11) NOT NULL DEFAULT '0',
  `des` varchar(80) DEFAULT '' COMMENT '描述',
  `data` varchar(10) CHARACTER SET utf8mb4 DEFAULT 'aaaa',
  `createdate` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '时间',
  `updatetime` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `uid` (`uid`),
  CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`uid`) REFERENCES `user` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8 COMMENT='ZZZZZZ'

获取创建history表语句:CREATE TABLE `orders_history` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ordertime` varchar(255) DEFAULT NULL,
  `total` double(5,2) DEFAULT NULL,
  `uid` int(11) NOT NULL DEFAULT '0',
  `des` varchar(80) DEFAULT '' COMMENT '描述',
  `data` varchar(10) CHARACTER SET utf8mb4 DEFAULT 'aaaa',
  `createdate` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '时间',
  `updatetime` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `uid` (`uid`),
  CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`uid`) REFERENCES `user` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8 COMMENT='ZZZZZZ'

新增字段创建表ddl:CREATE TABLE `orders_history` (`rowId` BIGINT(20) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `id` int(11) NOT NULL ,
  `ordertime` varchar(255) DEFAULT NULL,
  `total` double(5,2) DEFAULT NULL,
  `uid` int(11) NOT NULL DEFAULT '0',
  `des` varchar(80) DEFAULT '' COMMENT '描述',
  `data` varchar(10) CHARACTER SET utf8mb4 DEFAULT 'aaaa',
  `createdate` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '时间',
  `updatetime` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  KEY `idx_key` (`id`),
  KEY `uid` (`uid`),
  CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`uid`) REFERENCES `user` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8 COMMENT='ZZZZZZ'

获取表的insert触发器:
create trigger orders_bak after insert on orders for each row begin insert into orders_history (id,ordertime,total,uid,des,data,createdate,updatetime) values (NEW.id,NEW.ordertime,NEW.total,NEW.uid,NEW.des,NEW.data,NEW.createdate,NEW.updatetime); end

打印字段信息:
orders表中字段个数为:8

Process finished with exit code 0
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,444评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,421评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,036评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,363评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,460评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,502评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,511评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,280评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,736评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,014评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,190评论 1 342
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,848评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,531评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,159评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,411评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,067评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,078评论 2 352

推荐阅读更多精彩内容