連接mysql數(shù)據(jù)庫(kù)
① 導(dǎo)包:import pymysql
② 創(chuàng)建連接:
conn = pymysql.connect(host = 'localhost',port = 3306,user = 'root',password = 'xxx',db = 'xxx',charset='utf8')
③ 查詢操作:
sele=pd.read_sql('select * from t2 limit 3',conn)
④ 保存數(shù)據(jù)到數(shù)據(jù)庫(kù)時(shí)出現(xiàn):
No module named 'MySQLdb'
這是由于?MySQL-python?不支持 Python 3(MySQL-3.23 through 5.5 and Python-2.4 through 2.7 are currently supported)
于是?找到了一個(gè)替代——?PyMySQL。執(zhí)行?pip install PyMySQL
,將數(shù)據(jù)庫(kù)連接改為 :
create_engine("mysql+pymysql://scott:tiger@hostname/dbname"),接下來(lái)的操作就一切正常了。
舉個(gè)例子:
from sqlalchemy import create_engine?
#將數(shù)據(jù)寫入mysql的數(shù)據(jù)庫(kù),但需要先通過(guò)sqlalchemy.create_engine建立連接,且字符編碼設(shè)置為utf8,否則有些latin字符不能處理
conn = create_engine('mysql+pymysql://username:pwd@localhost:3306/interview?charset=utf8')
sele.to_sql('t2',conn,index=False,if_exists='append')
pd.read_sql('select * from t2',conn)








暫無(wú)數(shù)據(jù)