Use excle table to import mysql data
import pandas as pd
from sqlalchemy import create_engine
r=pd.read_excel('python.xlsx')
engine =create_engine('mysql+pymysql://username:user password@database address')#database database name, password user password
r.to_sql('python',con =engine,if_exists='replace',index=False)#The name of the table in the database,
print("Successfully imported into the database!")
Just a few sentences, but there may be many problems. Let me talk about the url format of create_engine first. Needless to say the user name and password, address:port is the ip address and port number to connect to MySQL (default localhost:3306), the database name is the database to be connected to, the character encoding is very important, if you want to insert Chinese, use utf8
Several parameters of to_sql:
- name is the table name
- con is connection
- if_exists: What to do if the table exists
- append: append
- replace: delete the original table, create a new table and add
- fail: do nothing
- index=False: Do not insert index index
Use mysql to export execle
import pandas as pd
from sqlalchemy import create_engine
connect=create_engine('mysql+pymysql://username:user password@database address')
sql = "SELECT * FROM user "
data = pd.read_sql(sql,connect)
writer = pd.ExcelWriter("hello_data.xlsx")
data.to_excel(writer,sheet_name = "data",index=None) #导出成excel
writer.save()
print("Successfully imported excle form!")
Prerequisites must install project components