从mysql获取结果后无法写入文件

时间:2018-06-06 06:07:01

标签: mysql python-3.x

我有以下代码从MySql获取一些结果并将它们写入文件。但注意到写入文件,我错过了什么?

import MySQLdb as dbapi
import sys
import csv
import xlwt
dbServer='127.0.0.1'
dbPass='Mydatabases#0'
dbSchema='myblog'
dbUser='root'
out='C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/outfile.txt'
dbQuery="SELECT link,repo_name,dataset_id,COALESCE (title, 'No data has been provided'),COALESCE (description, 'No data has been provided') FROM myblog.testseprator";   
db=dbapi.connect(host=dbServer,user=dbUser,passwd=dbPass)
cur=db.cursor()
cur.execute(dbQuery)
result=cur.fetchall() 
with open('out','w', encoding="utf-8") as f:
    writer = csv.writer(f,delimiter='\t')
    for row in result:
        writer.writerow(row)        
db.close();

1 个答案:

答案 0 :(得分:0)

您可以参考以下代码以获得所需的输出:

    import os
    import pymysql
    from pandas import DataFrame
    def connect_to_database(host,user,password,db,query):
        connection = pymysql.connect(host=host,
                         user=user,
                         password=password,                             
                         db=db,
                         cursorclass=pymysql.cursors.DictCursor)
        try:
            with connection.cursor() as cursor:
                c=cursor.execute(query)
                df = DataFrame(cursor.fetchall())  
        finally:
           connection.close()
        return df
        #this will return a pandas dataframe which you can directly convert to csv

获得数据帧后,您可以使用pandas的to_csv转换为csv文件。假设你调用了函数并将结果返回到“result”

    path='C:\\ProgramData\\MySQL\\MySQL Server 5.7\\Uploads\\'
    result.to_csv(os.path.join(path+r'output.csv'))
    #this will convert the result dataframe into file called "output"