python3 连接mysql执行sql语句

一、图解流程:(转)

111111

二、代码部分

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:suhan
#time:2020-06-09

import pymysql.cursors,sys,time

# sql执行函数。传入连接,游标,sql文件
def sqlExecuteFromFile (connect,cursor,SqlFile):
    # 记录成功和失败的语句
    fileTime = time.strftime("%Y-%m-%d", time.localtime())
    RetLog = "result" + fileTime + ".log"
    #打开sql语句的文件并一条条执行
    with open(SqlFile,'r',encoding='utf-8') as f:
        #记录成功执行的语句到文件中
        with open(RetLog, 'a+', encoding='utf-8') as fs:
            for SqlLine in f:
                execTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                try:
                    # 执行和记录
                    cursor.execute(SqlLine)
                    # 提交。执行一次提交一次。大量变更时只做一次提交,防止提交超时,失败。
                    connect.commit()
                    Ret = execTime + "##success##" + SqlLine
                    fs.write(Ret)

                # 错误的分类应该跟细一些,分为数据库执行错误和写文件错误;
                # commit成功了,写日志失败的情况,重新记录了已经成功的sql认为是失败的。
                except Exception as e:
                    #如果有失败就回滚并记录
                    connect.rollback()
                    #写的错误日志记录。
                    ErrorMessage = "Error {0}".format(str(e))
                    Ret = execTime + "##failure##" + ErrorMessage + "##" + SqlLine
                    fs.write(Ret)

    # 关闭游标
    cursor.close()

if __name__ == "__main__" :
    # 判断输入参数个数。0是py文件名,1表示第一个输入参数。
    if len(sys.argv) != 2:
        print("请输入sql文件的路径。")
        sys.exit(0)

    # sql文件名。
    SqlFile = sys.argv[1]

    # 连接数据库,port不能带引号
    connect = pymysql.connect(
        host='127.0.0.1',
        port=3306,
        user='root',
        passwd='8491510',
        db='suhantest'
    )

    try :
        # 获取游标
        cursor = connect.cursor()
    except Exception as ee:
        print("连接数据库失败")

    print("-------连接数据库成功,开始执行sql-------")
    # 读取文件执行sql
    sqlExecuteFromFile(connect,cursor,SqlFile)

    # # 执行查询的语句样例,留存。
    # effect_row = cursor.execute("select * from product_channel")
    # # 打印一条
    # print(cursor.fetchone())

    #关闭连接
    connect.close()
    print('sql全部执行完,查看resultxx.log确认是否有问题。')


三、参考

https://www.cnblogs.com/1832921tongjieducn/p/11128951.html
https://blog.csdn.net/guofeng93/article/details/53994112

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值