python数据库定时更新脚本

1. 概述

        通过python连接本地数据库,创建Html网页,生成数据库的表清单及每张表的结构、修改语句等。步骤如下:

1. 从git远程拉取代码
2. 读取数据库每张表结构,生成md文档
3. 为表结构md文档添加change log
4. 每张表结构md转为html
5. 构建首页导航

完整代码下载地址:databaseDesc.zip-Python文档类资源-CSDN下载python生成数据库管理脚本网页,1.从git远程拉取代码2.读取数据库每张表结构,生成m更多下载资源、学习资料请访问CSDN下载频道.https://download.csdn.net/download/Lynqwest/57055476

2. 代码实现

2.1 从git远程拉取代码 

def downloadGit(download_path,clone_path,branch_name):
    # 从远程仓库更新代码
    if os.listdir(download_path):
        print('git pull to ', download_path)
        repo = Repo(download_path)

        ## 切换到最新分支
        repo.git.checkout(branch_name)
        repo.git.pull()
        cur_branch = repo.git.branch()
        print('current branch ', cur_branch,' 代码正在拉取中...')
    # 从远程仓库下载代码
    else:
        print('clone from ', clone_path)
        Repo.clone_from(clone_path,to_path=download_path,branch='master')

2.2 读取数据库每张表结构,生成md文档


数据库表结构查询,生成表结构md文档
1. 连接数据库
2. 读取表名
3. 遍历表,读取表结构
4. 每张表保存为md文档
 

import pymysql
import os

print('hello world——convertSqlToMd')
###########################   1. 连接数据库   #############################
def connectSql():
    # 打开数据库连接
    db = pymysql.connect(
        host="host_name",
        port=port_name,
        user='user_name',
        password='password_name',
        database='database_name'
    )

    db = connectSql()
    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()
    # 使用 execute()  方法执行 SQL 查询
    cursor.execute("SELECT VERSION()")
    # 使用 fetchone() 方法获取单条数据fetchone/所有数据fetchall
    data = cursor.fetchall()
    print ("Database version : %s " % data)
 
    # 关闭数据库连接
    db.close()
###########################   2. 读取表名   ##################################
selTables = "select table_name from information_schema.tables where table_schema='database_name' "

cursor.execute(selTables)
tableNames = cursor.fetchall()

###########################   3. 遍历表,读取表结构   #############################
###########################   4. 每张表保存为md文档   #############################
colName= '| Field    |Type    | Collation    | Null    |Key    | Default    | Extra    |Privileges    | Comment    |'
colDel = '| ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- |'
try:
    for tableName in tableNames:
        # 遍历每张表
        tableName = tableName[0]
        # 描述表结构
        desTable = "show full columns from " + tableName
        # 执行表结构读取
        cursor.execute(desTable)
        tableStruc = cursor.fetchall()

        # 创建md文档,解析格式化数据
        with open(os.path.join(path , '%s.md'%tableName), 'w') as f:
            # 增加页面标题
            print(os.path.join(path , '%s.md'%tableName))
            f.writelines('## %s'%tableName + '\n')
            f.writelines('------ \n')
            f.writelines(colName + '\n')
            f.writelines(colDel + '\n')

            # 遍历该表结构每行
            for i in tableStruc:
                i = list(i)
                removeNone = ['null' if i == None else i for i in i]
                line = '|' + ' | '.join(removeNone) + ' | '

                f.writelines(line + '\n')
        f.close()

2.3 为表结构md文档添加change log

        组件代码结构如下,遍历该文件夹下所有时间日期的文件夹中的sql文件,sql文件名与实际表名一致,方便查找该表md文档,直接写入sql语句 

import datetime
import os
'''
1. 读取 DbScript组件 脚本语句
2. 添加到已有md文档中
'''
def addChangeLog(dbpath):

    ### md文档地址
    md_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'mySqlTabsMd')

    listdir =  os.listdir(dbpath)
    listdir.remove('deploy.yaml')
    listdir.sort(reverse=True)
    print('迭代文件夹:',listdir)

    for timedir in listdir:

        ### 遍历当前日期文件夹下 每个sql文件
        for foldername , subfolders , filenames in os.walk(dbpath +'\%s'%timedir):
              for filename in filenames:
                    if filename != 'rollback.sql':
                        ####### 读取表名 及 Sql 语句
                        tablename = filename.split('.')[0].split('-')[0]
                        filepath = os.path.join(foldername, filename)
                        sqlfile = open(filepath, "r",encoding='utf-8').read()
               
                     ####  将 change log 写进对应表md中
                    try:
                        md_file_path = os.path.join(md_path,tablename+'.md')

                        with open(md_file_path,'a') as f:
                            # 添加 时间
                            f.writelines('\n')
                            f.writelines(' - '+ timedir + '\n')
                      
                            f.writelines("```mysql \n")
                            f.write(sqlfile+ '\n')
                            f.writelines("```")
                        f.close()
                    except :
                        pass

2.4 每张表结构md转为html

        将每一个表结构md文档转化为html文件,方便首页导航直接跳转。其中exts为markdown类型扩展包,能够将md文档中的样式正常加载转换为Html的样式,github.css及dracula.css为样式文件,使html样式正常/代码高亮显示等..

exts = ['markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.tables', 'markdown.extensions.toc']
'''
md文档转为html格式
1. 格式化html页面
2. md————>html
3. 输出保存html
'''

import markdown
import os
print('hello world——md2html')
####### 1. 读取文件
def readFile(exts):
    path = os.path.dirname(os.path.abspath(__file__))
    print(path)
    ### 变量定义
    html = '''<!DOCTYPE html>
              <head>
                  <meta charset="UTF-8">
                  <meta name="viewport" content="width=device-width, initial-scale=1, minimal-ui">
                  <title>{}</title>

                   <link rel="stylesheet" href="../css/github.css">
                   <link rel="stylesheet" href="../css/dracula.css">
              </head>
              <body>
                   <article class="markdown-body">
                      {}
                  </article>
              </body>
          </html>
          '''
    for input_file in os.listdir(path+'\mySqlTabsMd'):
        table_name = input_file.split('.')[0]
        output_file =os.path.join(path,'mySqlTabsHtml' , table_name +'.html')
        print(input_file,output_file)
        md_file_path  = os.path.join(path,'mySqlTabsMd',input_file)
        md_file = open(md_file_path,"r")
        html_body_txt = md_file.read()
        md_file.close()

        md2html(table_name,html_body_txt,output_file,html,exts)

####### 2. md文档转换,html文件保存
#######    参数:标题,Htmlbody内容,输出路径,html结构参数,md扩展包
def md2html(title,html_body_txt,output_file,html,exts):

    ### md文件转为 html
    md = markdown.Markdown(extensions = exts)
    html_body = md.convert(html_body_txt)
    ### html文件保存
    html = html.format(title, html_body)
    html_file = open(output_file,"w",encoding='utf-8')
    html_file.write(html)
    html_file.close()

2.5 构建首页导航

        读取数据库所有表名,循环换行写入index.md,调用md2html 方法,生成首页的Html文件

# 执行sql语句
db = connectSql()
cursor = db.cursor()
selTables = "select table_name from information_schema.tables where table_schema='zytbmdb' "
cursor.execute(selTables)
tableNames = cursor.fetchall()

注意, title为表名,最好md文档也保持同名

for i in tableNames:
    title =  i[0]
    link = 'mySqlTabsHtml/%s.html'%title
    content = "- [{}]({})".format(title,link)
    print(content)
    f.write(content+'\n')

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Python的pyodbc库和Windows定时任务来实现将局域网下的主机的SQL Server数据库定时更新到一台主机上。具体步骤如下: 1. 安装pyodbc库,可以使用pip install pyodbc命令进行安装。 2. 编写Python脚本,在脚本中使用pyodbc库连接远程主机的SQL Server数据库,并将数据更新到本地主机的数据库中。示例代码如下: ```python import pyodbc # 连接远程主机的SQL Server数据库 conn = pyodbc.connect('DRIVER={SQL Server};SERVER=远程主机名称;DATABASE=数据库名称;UID=用户名;PWD=密码') cursor = conn.cursor() # 查询数据并更新到本地主机的数据库中 cursor.execute('SELECT * FROM 名') data = cursor.fetchall() # 连接本地主机的SQL Server数据库 conn_local = pyodbc.connect('DRIVER={SQL Server};SERVER=本地主机名称;DATABASE=数据库名称;UID=用户名;PWD=密码') cursor_local = conn_local.cursor() # 将数据更新到本地主机的数据库中 for row in data: cursor_local.execute('INSERT INTO 名 VALUES (?, ?, ?)', row) conn_local.commit() ``` 3. 配置Windows定时任务,让Python脚本定时执行。可以使用Windows的任务计划程序来创建定时任务,设置Python脚本的执行时间和执行方式即可。 需要注意的是,此方法需要保证远程主机的SQL Server数据库与本地主机的SQL Server数据库结构相同,否则数据更新可能会失败。另外,需要保证远程主机的SQL Server数据库可以被本地主机访问到。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值