您的位置:首页 > 编程语言 > Python开发

python读取mysql数据表和字段注释并自动生成查询语句

2019-09-19 14:10 609 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/Xkiller1/article/details/101021289

目前mysql的数据库管理工具在查看字段注释时无法像PL/SQL那么方便,mysql执行select * from table后,还得转到数据表的DDL页面查看字段注释,非常不方便,因此我用python写了个脚本,可以读取mysql数据表和字段注释并自动生成查询语句。

废话不多说,直接上代码。

import pymysql

class GetMysqlTableComments():
    def __init__(self, host, user, password, database,port,charset):
        self.db = pymysql.connect(host=host, user=user, password=password, port=port, database=database, charset=charset)
        self.cursor = self.db.cursor()

    def get_tables(self, database_name):
        sqlstr = ''
        # 查询mysql表名和注释
        self.cursor.execute(
            'select table_name,table_comment from information_schema.TABLES where TABLE_SCHEMA=%s order by table_name',
            database_name)
        return_tables = self.cursor.fetchall()
        for tabledata in return_tables:
            return_columns = self.get_columns(tabledata[0])
            sqlstr = sqlstr +'\n-- '+tabledata[1]+'\n'
            sqlstr = sqlstr + 'select\n' + return_columns + '\n from ' + tabledata[0] + ';\n'
        return sqlstr

    def get_columns(self, table_name):
        # 查询mysql表字段注释
        self.cursor.execute('select column_name,column_comment from information_schema.COLUMNS where TABLE_NAME=%s',
                            table_name)
        return_columns = self.cursor.fetchall()
        columnstr = ''
        for columndata in return_columns:
            #列名加上`是为了防止列名使用了mysql关键字时会报sql语法错误
            columnstr = columnstr+"`"+columndata[0]+"`"
            if columndata[1].strip() != '':
                # 若表字段注释里含有:、-、,、空格等符号,会报sql语法错误,可以使用replace函数替换特殊符号。程序自动改虽然方便,但是注释可读性不太好,建议手动修改。
                comment = columndata[1].replace('-', '')
                comment = comment.replace(':', ',')
                comment = comment.replace(',', ',')
                comment = comment.replace(' ', ',')
                comment = comment.replace('=', ',')
                comment = comment.replace('(', '(')
                comment = comment.replace(')', ')')
                comment = comment.replace('[', '(')
                comment = comment.replace(']', ')')
                comment = comment.replace('|', '、')
                comment = comment.replace('"', '')
                comment = comment.replace('.', '、')
                comment = comment.replace('/', '、')
                comment = comment.replace('{', '(')
                comment = comment.replace('}', ')')
                comment = comment.replace('?', '?')
                # 若发现其它符号引起的sql语法错误,自己继续补充即可
                columnstr = columnstr + ' as ' + comment
            columnstr += ',\n'
        # 去掉最后一列的逗号和换行符
        return columnstr[:-2]

    def closedb(self):
        self.cursor.close()
        # 关闭数据库
        self.db.close()

if __name__ == '__main__':
    #数据库地址
    host = '192.168.56.1'
    #数据库端口
    port=3306
    #数据库用户名
    user = 'root'
    #密码
    password = 'p@ssword@root'
    #数据库名称
    database = 'test_interface'
    #字符集
    charset = 'utf8'
    my_database = GetMysqlTableComments(host, user, password, database,port,charset)
    sqlstr = my_database.get_tables(database)
    my_database.closedb()
    #生成的sql打印到控制台
    print(sqlstr)
    #生成的sql保存到文件
    file_path='get_mysql.sql'
    with open(file_path,'w') as file:
        file.write(sqlstr)

执行后可以看到已生成sql文件。

这下查看字段注释就不用到数据表DDL页面了。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: