import pymysql import pandas as pd from pandas import DataFrame from sqlalchemy import create_engine class mysql(): def __init__(self,host,port,user,password,database): self.host=host self.port=port self.user=user self.password=password self.database=database self._conn = None self.Connect() def Connect(self): if not self._conn: self._conn=pymysql.connect(host=self.host,port=self.port,user=self.user,password= self.password,database=self.database,charset='utf8') #查询数据库表中的所有数据 def Query(self,sql): self.cursor = self._conn.cursor() self.excute = self.cursor.execute(sql) row_all = self.cursor.fetchall() index = self.cursor.description new_index=[] for i in range(len(index)): new_index.append(index[i][0]) data_sql=DataFrame(list(row_all),columns=new_index) return data_sql #数据保存到数据库 def my_keep(self,data,filename): db_url = ( '{driver}://{user}:{pwd}@{host}:{port}/{name}?charset=utf8'.format(driver='mysql+pymysql', user=self.user, port=self.port, pwd=self.password, host=self.host, name=self.database)) my_engine = create_engine(db_url) pd.io.sql.to_sql(data, filename, my_engine, schema=self.database, if_exists='replace', index=True,index_label=None) def my_close(self): self.cursor.close() self._conn.close()