当前位置:网站首页>Pandas connection database read / write file

Pandas connection database read / write file

2022-06-10 02:49:00 It's a fish, a small meatball, a duck

install

Open the little skin , Create a database and table

sqlalchemy( To connect to the database , Use pip install sqlalchemy)

Use

import pandas as pd
# introduce pymysql
import pymysql
from sqlalchemy import create_engine
sql="select * from stu"
engine = create_engine('mysql+pymysql://root:[email protected]:3306/pandas')

res = pd.read_sql_query(sql, engine)

res

sql="select * from stu"

stu Is the name of the table to be read from our database

create_engine('mysql+pymysql://root:[email protected]:3306/pandas')

root Is the user name

123456 It's the user password , Fill in your own database password

pandas Is the name of our database , You need to create it yourself

So we can read the data in our table

res = pd.read_sql_query(sql, engine)

 read_sql_query Reading table ,sql It's the top sql sentence

If we want to write data to the database , Use the following command :

df.to_sql('user',engine)

df Is the file to write ,user Is the table to write data to , The database cannot have duplicate tables

give an example :

Save the table data to the database , Then read out the data

import pandas as pd
# introduce pymysql
import pymysql
from sqlalchemy import create_engine
sql="select * from stu"
engine = create_engine('mysql+pymysql://root:[email protected]:3306/pandas')
 
res = pd.read_sql_query(sql, engine)
data=[[1,' Wang Yibo ','2103A',80],[2,' Xiao Zhan ','2103A',90],[3,' Delireba ','2103A',89]]
columns=[' Student number ',' full name ',' class ',' achievement ']
df=pd.DataFrame(data=data,columns=columns)
df.to_sql('user',engine)

This writes the data to the database , Read out the data

#  export 
sqluser='select * from user'
use=pd.read_sql(sqluser,engine)
use

Be careful : Write data and export data must be written separately , Otherwise, duplicate errors will be reported

原网站

版权声明
本文为[It's a fish, a small meatball, a duck]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206100240062883.html