程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

How to store dataframe data in pandas into MySQL

編輯:Python

problem :

How to make Pandas Medium DataFrame Data import to MySQL In the database ?
So how to achieve it ?


Implementation code :

To prevent code redundancy, I wrote a class directly
When using, you only need to modify the passed parameters

import pymysql
from sqlalchemy import create_engine
import pandas as pd
""" Paste directly into brackets host='127.0.0.1', port='3306', user="root", pasword="123456", db=" Database name ", tb=" Table name ", df="dataframe data " """
#pandas dataframe Data is loaded directly into mysql in 
class PDTOMYSQL:
def __init__(self,host,user,pasword,db,tb,df,port='3306'):
self.host = host
self.user = user
self.port = port
self.db = db
self.password = pasword
self.tb = tb
self.df = df
sql = 'select * from '+self.tb
conn = create_engine('mysql+pymysql://'+self.user+':'+self.password+'@'+self.host+':'+self.port+'/'+self.db)
df.to_sql(self.tb, con=conn, if_exists='replace')
self.pdata = pd.read_sql(sql,conn)
def show(self):# Show datasets 
return print(self.pdata)

Test it :

#data It's test data 
data = {

'state':['Ohio','Ohio','Ohio','Nevada','Nevada'],
'year':[2000,2001,2002,2001,2002],
'pop':[1.5,1.7,3.6,2.4,2.9]
}
# hold data convert to dataframe data 
frame = pd.DataFrame(data)
t = PDTOMYSQL(
host='127.0.0.1',
port='3306',
user="root",
pasword="123456",
db="data_base",
tb="t_demo",
df=frame)
t.show()


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved