Writes pandas's dataframe data to the MySQL database + sqlalchemy
[Python]View PlainCopyprint?
- IMPORT PANDAS AS PD  
- from sqlalchemy import create_engine
-   
- # #将数据写入mysql的数据库, However, you need to establish a connection through Sqlalchemy.create_engine, and the character encoding is set to UTF8, otherwise some Latin characters cannot handle
- ' mysql+mysqldb://root:[email protected]:3306/ Databasename?charset=utf8 ')
- pd.io.sql.to_sql (thedataframe, ' DatabaseName ', if_exists= ' append ')
Import pandas as Pdfrom sqlalchemy import create_engine# #将数据写入mysql的数据库, but you need to establish a connection via Sqlalchemy.create_engine first, And the character encoding is set to UTF8, otherwise some Latin characters cannot handle yconnect = Create_engine (' Mysql+mysqldb://root:[email protected]:3306/databasename? Charset=utf8 ') pd.io.sql.to_sql (thedataframe, ' tablename ', Yconnect, schema= ' databasename ', if_exists= ' append ')
In To_sql,
The first parameter, Thedataframe, is the PD dataframe that needs to be imported,
The second parameter, TableName, is the name of the table in the database that will be imported
The third parameter, Yconnect, is the interface to start the database, and after the release of PD 1.9, all but sqllite need to be set by SQLAlchemy
The fourth parameter databasename is the name of the database to be imported
The fifth parameter if_exists= ' append ' means that if the table tablename exists, the data is added to the back of the table
Sqlalchemy.create_engine is the database engine
Explanation of (' Mysql+mysqldb://root:[email Protected]:3306/databasename?charset=utf8 ')
MySQL is the database to use
MYSQLDB is an interface program that needs to be used
Root is the database account
Password is the database password
LocalHost is the address of the server where the database resides, this is the local
3306 is the port that MySQL occupies
Elonuse is the name of the database.
Charset=utf8 is to set the encoding of the database, so as to prevent the Latin character not recognized and error
Transfer from http://blog.csdn.net/biboshouyu/article/details/54139641
Writes pandas's dataframe data to the MySQL database + sqlalchemy