300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > python导出mysql数据_使用python导出mysql数据为csv文件

python导出mysql数据_使用python导出mysql数据为csv文件

时间:2020-09-01 12:54:55

相关推荐

python导出mysql数据_使用python导出mysql数据为csv文件

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

python3.7

pymysqlfrom pyecharts import Pie

import pymysql

import csv

import time

class View:

def __init__(self):

# 数据库配置

self.host = 'localhost'

self.database = '东方财富'

self.table = '上证指数_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)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。