jupyter notebook保存数据到mysql问题及解决

连接mysql数据库

① 导包:import pymysql

② 创建连接:

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)
 

④ 保存数据到数据库时出现: No module named 'MySQLdb'

查了一下,是由于 MySQL-python 不支持 Python 3(MySQL-3.23 through 5.5 and Python-2.4 through 2.7 are currently supported)。

   于是 找到了一个替代—— PyMySQL。执行 pip install PyMySQL,将数据库连接改为 create_engine("mysql+pymysql://scott:tiger@hostname/dbname"),接下来的操作就一切正常了。

举栗子:

from sqlalchemy import create_engine 

#将数据写入mysql的数据库,但需要先通过sqlalchemy.create_engine建立连接,且字符编码设置为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)

猜你喜欢

转载自blog.csdn.net/Dorisi_H_n_q/article/details/81413292