1. 程式人生 > >python通過pandas讀取mysql資料庫表

python通過pandas讀取mysql資料庫表

下午研究了下windows下快速操作mysql的方法
不想裝workbench,因為要裝VS2015
在官網下了一個mysql-shell,用起來還不錯,但是我沒有更多的許可權,select into outfile的時候沒有許可權
mysql-shell官網下載是個還個還不錯的互動式命令列,輸入\connect [email protected] 直接登陸之後\sql轉入sql模式,更多的沒看。

想到直接用python連線mysql資料庫讀資料之後存下來或者操作都可以。嘗試使用pandas
很多文章都提到MySQLdb這個包,但是py3下沒有,懷疑可能是py2的產物,但是找到了一個替代品

import pymysql
import pandas as pd
con=pymysql.connect('genome-mysql.cse.ucsc.edu','genome','','mm10')
df=pd.read_sql('SELECT * FROM refGene',con=con)

這樣就可以用panda的read_sql方法了,注意用read_sql_table還是會報錯。
其實UCSC上所謂的GenePred格式就是從refGene這個表中選了一部分欄位出來

>>> df=pd.read_sql_table('refGene',con)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\nilab\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\io\sql.py", line 234, in read_sql_table
    raise NotImplementedError("read_sql_table only supported for "
NotImplementedError: read_sql_table only supported for SQLAlchemy connectable.

應該是安裝sqlalchemy之後就可以直接讀表

from sqlalchemy import create_engine  
engine = create_engine("mysql://root:[email protected]/test", pool_size=5,echo_pool=True)  

conn = engine.connect()

table_name = 'user'
datas = pd.read_sql_table(table_name, conn)

其他參考:
mysql內容轉換到sqlite3

將資料寫入到本地sqlite3

>>> import sqlite3
>>> con=sqlite3.connect('mm10.db')
>>> df.to_sql('refGene',con)
>>> con.close()