Python的pandas包對錶格化的數據處理能力很強,而SQL數據庫的數據就是以表格的形式儲存,所以常常將sql數據庫裏的數據直接讀取爲dataframe,分析操做之後再將dataframe存到sql數據庫中。而pandas中的read_sql和to_sql函數就能夠很方便得從sql數據庫中讀寫數據。html
參見pandas.read_sql的文檔,read_sql主要有以下幾個參數:python
import pandas as pd import pymysql import sqlalchemy from sqlalchemy import create_engine # 1. 用sqlalchemy構建數據庫連接engine connect_info = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8'.format(DB_USER, DB_PASS, DB_HOST, DB_PORT, DATABASE) #1 engine = create_engine(connect_info) # sql 命令 sql_cmd = "SELECT * FROM table" df = pd.read_sql(sql=sql_cmd, con=engine) # 2. 用DBAPI構建數據庫連接engine con = pymysql.connect(host=localhost, user=username, password=password, database=dbname, charset='utf8', use_unicode=True) df = pd.read_sql(sql_cmd, con)
解釋一下 #1: 這個是sqlalchemy中連接數據庫的URL格式:dialect[+driver]://user:password@host/dbname[?key=value..]
。dialect表明書庫局類型,好比mysql, oracle, postgresql。driver表明DBAPI的名字,好比psycopg2,pymysql等。具體說明能夠參考這裏。此外因爲數據裏面有中文的時候就須要將charset設爲utf8。mysql
參見pandas.to_sql函數,主要有如下幾個參數:sql
df.to_sql(name='table', con=con, if_exists='append', index=False, dtype={'col1':sqlalchemy.types.INTEGER(), 'col2':sqlalchemy.types.NVARCHAR(length=255), 'col_time':sqlalchemy.DateTime(), 'col_bool':sqlalchemy.types.Boolean })
注:若是不提供dtype,to_sql會自動根據df列的dtype選擇默認的數據類型輸出,好比字符型會以sqlalchemy.types.TEXT類型輸出,相比NVARCHAR,TEXT類型的數據所佔的空間更大,因此通常會指定輸出爲NVARCHAR;而若是df的列的類型爲np.int64時,將會致使沒法識別並轉換成INTEGER型,須要事先轉換成int類型(用map,apply函數能夠方便的轉換)。數據庫
參考:
http://docs.sqlalchemy.org/en/latest/core/type_basics.html#sql-standard-and-multiple-vendor-types
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql.html
http://docs.sqlalchemy.org/en/latest/core/engines.html
http://docs.sqlalchemy.org/en/latest/core/type_basics.html#sql-standard-and-multiple-vendor-types
http://stackoverflow.com/questions/30631325/writing-to-mysql-database-with-pandas-using-sqlalchemy-to-sql
http://stackoverflow.com/questions/5687718/how-can-i-insert-data-into-a-mysql-database
http://stackoverflow.com/questions/32235696/pandas-to-sql-gives-unicode-decode-error
http://stackoverflow.com/questions/34383000/pandas-to-sql-all-columns-as-nvarcharoracle