python执行mysql命令并导出结果到文本

2017-04-05  本文已影响0人  相关知情人士

脚本:

# -*- coding: utf-8 -*-
import MySQLdb
import sys  #为了给脚本添加参数
 
if __name__ == '__main__':
  #连接数据库
    conn = MySQLdb.connect(host="dz-233", user="abc", passwd="def", db="gh", charset="utf8")
    cursor = conn.cursor()

 #接受第一个参数 0 是脚本名
date = sys.argv[1]

topRateSql = 'select DISTINCT "rate" as tag,shop_id from tb_top_rate_secret_stat where date = %s and rate_top_num <= 100 and shop_id not in (select distinct(shop_id) from CAUser.tb_user_secret_relation where status >= 0)'

topSql = 'select distinct "top" as tag, shop_id from tb_top_secret_stat where date = %s and top_num <= 100 and shop_id not in (select distinct(shop_id) from CAUser.tb_user_secret_relation where status >= 0)'

shopRelationSql = 'select distinct(shop_id) from CAUser.tb_user_secret_relation where user_id="TSU" and status = 10 and last_modify_time >= "2017-04-01"'

cursor.execute(shopRelationSql)

rows1 = cursor.fetchall()
## 写入文件
with open("./result" + date, 'wb+') as f:
    for row in rows1:
        f.write('%s\n' % row[0])

#关闭资源
cursor.close()
conn.close()

备注 :


上一篇 下一篇

猜你喜欢

热点阅读