当前位置: 首页 > 后端技术 > Python

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

时间:2023-03-25 22:56:28 Python

使用python将mysql数据导出为csv文件python3.7pymysqlfrompyechartsimportPieimportpymysqlimportcsvimporttimeclassView:def__init__(self):#数据库配置self.host='localhost'self.database='东方财富'self.table='上证指数2019_2'self.user='root'self.password='yjcyjc'self.port=3306#csvstorageself.path='.'self.inputfilename='input.csv'self.csvfilename='datas.csv'self.logfilename='run.log'defrun(self):strat=time.time()rows=self.get_input()print(len(行))以open('{}/{}'.format(self.path,self.csvfilename),'a',encoding='utf_8_sig',newline='')作为csvfile:writer=csv.writer(csvfile)writer.writerows(rows)#forrowinrows:#self.save_data(row)end=time.time()self.runtime=end-stratdefget_input(self):#打开数据库连接db=pymysql.connect(选择f.host,self.user,self.password,self.database,self.port)#使用cursor()方法创建游标对象cursorcursor=db.cursor()#使用execute()方法执行SQLqueriescursor.execute("SELECTlist_url,url,name,post_time,contentfrom{}".format(self.table))#使用fetchone()方法获取单条数据。results=cursor.fetchall()#关闭数据库连接db.close()returnresultsdefsave_data(self,item):'''savefile'''print('-',end='')withopen('{}/{}'.format(self.path,self.csvfilename),'a',encoding='utf_8_sig',newline='')作为csvfile:writer=csv.writer(csvfile)writer.writerow(item)@propertydeftime(self):return'Totaltimespent:{}seconds'.format(self.runtime)if__name__=='__main__':view=View()#实例化对象view.run()print(view.时间)