设为首页 加入收藏

TOP

Python导出MySQL数据库中表的建表语句到文件(一)
2018-03-18 16:21:21 】 浏览:165
Tags:Python 导出 MySQL 数据库 中表 语句 文件

为了做数据对象的版本控制,需要将MySQL数据库中的表结构导出成文件进行版本化管理,试写了一下,可以完整导出数据库中的表结构信息


# -*- coding: utf-8 -*-
import os
import pymysql



class DBTool:


    conn = None
    cursor = None


    def __init__(self,conn_dict):
        self.conn = pymysql.connect(host=conn_dict['host'],
                                    port=conn_dict['port'],
                                    user=conn_dict['user'],
                                    passwd=conn_dict['password'],
                                    db=conn_dict['db'],
                                    charset=conn_dict['charset'])
        self.cursor = self.conn.cursor()



    def execute_query(self, sql_string):
        try:
            cursor=self.cursor
            cursor.execute(sql_string)
            list = cursor.fetchall()
            cursor.close()
            self.conn.close()
            return list
        except pymysql.Error as e:
            print("mysql execute error:", e)
            raise


    def execute_noquery(self, sql_string):
        try:
            cursor = self.cursor
            cursor.execute(sql_string)
            self.conn.commit()
            self.cursor.close()
            self.conn.close()
        except pymysql.Error as e:
            print("mysql execute error:", e)
            raise


def main():
    conn_dict = {'host': '127.0.0.1', 'port': 3306, 'user': '******', 'password': '******', 'db': 'test', 'charset': 'utf8'}
    conn = DBTool(conn_dict)
    sql_gettables = "select table_name from information_schema.`TABLES` WHERE TABLE_SCHEMA = 'databas_name';"
    list = conn.execute_query(sql_gettables)


    # 文件目标路径,如果不存在,新建一个
    mysql_file_path = 'D:\mysqlscript'
    if not os.path.exists(mysql_file_path):
        os.mkdir(mysql_file_path)


    mysqldump_commad_dict = {'dumpcommad': 'mysqldump --no-data ', 'server': '127.0.0.1', 'user': '******',
                            'password': '******', 'port': 3306, 'db': 'databse_name'}


    if list:
        for row in list:
            print(row[0])
            # 切换到新建的文件夹中
           

首页 上一页 1 2 3 下一页 尾页 1/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇MySQL 8.0 新增SQL语法对窗口函数.. 下一篇es的索引合并

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目