美文网首页
python执行mysql命令并导出结果到文本

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

作者: 相关知情人士 | 来源:发表于2017-04-05 17:49 被阅读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()
    

    备注 :

    • python脚本应该比shell学起来写起来简单,可以用IDEA,同时也更强大多面,选择和方向很重要
    • 如有错误可以提出来,本人实战经验还需慢慢积累总结
    • 在服务器上用vim在不熟练的情况下,编辑测试起来好麻烦,搞了好久的IDEA 远程发布本地python,并到服务器上运行的方式,因为一些坑失败了,以后有时间继续搞

    相关文章

      网友评论

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

          本文链接:https://www.haomeiwen.com/subject/dqdxattx.html