简体   繁体   English

使用Python将数据从MySQL表保存到文本文件

[英]Saving data from MySQL table to a text file with Python

So I have a mysql table and I am trying to take each element from one of the fields of the table. 所以我有一个mysql表,我试图从表的一个字段中取出每个元素。 The field and table are both called "keywords". 字段和表都称为“关键字”。 In the field there are many different random words and I am trying to take all of those and save them to a text file. 在该字段中有许多不同的随机单词,我试图采取所有这些并将它们保存到文本文件中。 Any help on how to implement this would be great, here is what I have so far. 关于如何实现这一点的任何帮助都会很棒,这是我到目前为止所做的。

#!/usr/bin/env python
import MySQLdb


db = MySQLdb.connect(host="", user="", passwd="", db="")
cursor = db.cursor()
sql = """SELECT DISTINCT keywords FROM keywords"""
cursor.execute(sql)
cursor.fetchall()
db.close()

for s in sql:
   tweets = open("keywords.txt", "w")

What I was thinking is to turn what sql fetches into a list if possible and write that to the file. 我想的是如果可能的话将sql提取到列表中并将其写入文件。 But I am open to any suggestions, thanks. 但我对任何建议持开放态度,谢谢。

Something like this should work: 这样的事情应该有效:

import MySQLdb

db = MySQLdb.connect(host="", user="", passwd="", db="")
cursor = db.cursor()
sql = """SELECT DISTINCT keywords FROM keywords"""
tweets = open("keywords.txt", "w")
cursor.execute(sql)
for row in cursor:
   print>>tweets, row[0]
tweets.close()
db.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM