如何读取数据库并把数据导出CSV文档

import csv
import os

import pymysql
from pprint import pprint
# import pandas


class Test_myqsl(object):
    def __init__(self):
        #读取数据库和建立游标对象
        self.connect = pymysql.connect(host="127.0.0.1",
                                       port=3306,
                                       user="root",
                                       password="password",
                                       database="databases",
                                       charset="utf8")
        self.cursor = self.connect.cursor(cursor=pymysql.cursors.DictCursor)

        # 关闭数据库和游标对象

    def __del__(self):
        self.connect.close()
        self.cursor.close()

    def write(self):


        file = 'code.csv'
        productID = ['id','list_1','list_1','list_1','list_1','list_1']
        rows = self.read()
        with open(file, "w+",encoding='utf-8', newline="") as csv_file:
            f_csv = csv.DictWriter(csv_file, productID)
            f_csv.writeheader()
            f_csv.writerows(rows)



    def read(self):
        # 读取数据库的所有数据
        data = self.cursor.execute("""select * from user""")
        field_2 = self.cursor.fetchall()
        return field_2
    # 封装


def main():
    write = Test_myqsl()
    write.write()


if __name__ == '__main__':
    main()


    原文作者:yinghuochong124
    原文地址: https://blog.csdn.net/yinghuochong124/article/details/123582045
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞