mysql连接查询并写到txt

 1 import pymysql
 2 import time
 3 
 4 def logger(msg):
 5     print("[%s] %s" % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), msg))
 6 
 7 host = 'xxxxx'
 8 user = 'xxxxxxx'
 9 password = 'xxxx'
10 database = 'xxxx'
11 # 打开数据库连接
12 mysql_connect = pymysql.connect(host=host, user=user, password=password, db=database, port=3306, charset="utf8")
13 
14 if __name__ == '__main__':
15     sql = "SELECT * FROM marbleuser.article where content_type=1;"
16     # 使用cursor()方法获取操作游标
17     cursor = mysql_connect.cursor()
18     logger('开始查询')
19     # 使用execute方法执行SQL语句
20     cursor.execute(sql)
21     # 使用 fetchone() 方法获取一条数据
22     # 使用 fetchall() 方法获取所有数据
23     values = cursor.fetchall()
24     mysql_connect.commit()
25     logger('开始写到txt')
26     for i in values:
27         article_id = i[0]
28         with open(file='articleId.txt', mode='a+', encoding='utf-8') as f:
29             f.writelines(article_id + '\n')
30     #关闭数据库连接
31     mysql_connect.close()
32     logger('运行结束')

 

posted @ 2020-05-07 15:11  DaiYanxi  阅读(209)  评论(0)    收藏  举报