乐趣区

关于python:使用python导出mysql数据为csv文件

应用 python 导出 mysql 数据为 csv 文件
python3.7
pymysql

from pyecharts import Pie
import pymysql
import csv
import time

class View:
    def __init__(self):
        # 数据库配置
        self.host = 'localhost'
        self.database = '西方财产'
        self.table = '上证指数 2019_2'
        self.user = 'root'
        self.password = 'yjcyjc'
        self.port = 3306

        # csv 贮存
        self.path = '.'
        self.inputfilename = 'input.csv'
        self.csvfilename = 'datas.csv'
        self.logfilename = 'run.log'


        

    def run(self):
        strat = time.time()


        rows=self.get_input()
        print(len(rows))

        with open('{}/{}'.format(self.path, self.csvfilename), 'a', encoding='utf_8_sig', newline='') as csvfile:
            writer = csv.writer(csvfile)
            writer.writerows(rows)

        # for row in rows:
        #     self.save_data(row)

        end = time.time()

        self.runtime = end - strat

    def get_input(self):
        # 关上数据库连贯
        db = pymysql.connect(self.host, self.user, self.password, self.database, self.port)

        # 应用 cursor() 办法创立一个游标对象 cursor
        cursor = db.cursor()

        # 应用 execute()  办法执行 SQL 查问
        cursor.execute("SELECT list_url,url, name,post_time,content from {}".format(self.table))

        # 应用 fetchone() 办法获取单条数据.
        results = cursor.fetchall()

        # 敞开数据库连贯
        db.close()

        return results

    def save_data(self, item):
        '''保留文件'''
        print('-', end='')
        with open('{}/{}'.format(self.path, self.csvfilename), 'a', encoding='utf_8_sig', newline='') as csvfile:
            writer = csv.writer(csvfile)
            writer.writerow(item)

    @property
    def time(self):
        return '总共用时:{} 秒'.format(self.runtime)


if __name__ == '__main__':
    view = View()  # 实例化对象
    view.run()
    print(view.time)
退出移动版