将Mysql数据存储在文本文件python中

时间:2019-02-25 09:27:38

标签: python

import mysql.connector

mydb = mysql.connector.connect(host="localhost", user="", passwd="", db="world")
cursor = mydb.cursor()

file = open('C:\\test\\File.txt', 'w')
file_content = file.write()


query = "SELECT * FROM city where name='kabul'"

cursor.execute(query, (file_content,))

mydb.commit()
mydb.close()

这里我将数据存储在文本文件中,但是出错 名称'file_content' is not defined

1 个答案:

答案 0 :(得分:0)

我假设您要从MySQL提取所有行,然后在文件中进一步写入row-data

import mysql.connector

mydb = mysql.connector.connect(host="localhost", user="", passwd="", db="world")
cursor = mydb.cursor()

file_to_use = open('C:\\test\\File.txt', 'w+')

query = "SELECT * FROM city where name='kabul'"

cursor.execute(query)
row_data = cursor.fetchone()
while row_data is not None:
    file_to_use.write(str(row_data))
    file_to_use.write("\n")
    row_data = cursor.fetchone()
file_to_use.close()
mydb.commit()
mydb.close()

这会将提取的tuplerow_data)写入文本文件,每一行都换行。