python优雅执行SQL模板语句

有时候python执行sql语句会存在变量,那就需要对sql语句格式化。但是如果语句非常复杂,有时候还得更改。还要去改脚本里面sql语句就显得很笨,我们可以单独把sql语句保存成另外一个文件,做完模板。在执行的时候就可以直接从这个模板读取,在格式化后再执行语句就可以了。当然最后的结果也可以保存到execl,在发送邮件给相关的人,以前我就是定时导数据给运营人员的。

代码:

import sysimport MySQLdbimport yamldef readYml(file):   #读取yaml文件   with open(file) as fd:       res = yaml.safe_load(fd)    return res    def connMysql(host,user,dbpass,dbname,port=3306):    # 建立数据库连接    try:        conn = MySQLdb.connect(host=host, user=user, passwd=dbpass, db=dbname, port=port, charset='utf8')    except Exception as e:        print(e)        sys.exit()    cur = conn.cursor()    return conn, curdef execMysql(cursor, mysqlstr):    # 获取游数据库标.    cursor.execute('SET time_zone = "+8:00"')    cursor.execute(mysqlstr)    res = cursor.fetchall()    return resif __name__ == "__main__":        conn, cur = connMysql("192.168.0.x", "xx", "xx",                                   "xx")    tmpdict = readYml("mysql1.tmp")    sqlstr = tmpdict["mysqltmp"]    print(sqlstr)    sqlstr = sqlstr.format(num=10) # 传入参数到sql语句    res = execMysql(cur, sqlstr)    print(res)

sql模板文件:

mysqll1.tmp

mysqltmp: "SELECT * FROM xhw.t_goods          LIMIT {num};          "

执行结果:


发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章