使用 MySQL 的 Pandas 0.20.2 to_sql()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44933704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas 0.20.2 to_sql() using MySQL
提问by elPastor
I'm trying to write a dataframe to a MySQL table but am getting a (111 Connection refused)
error.
我正在尝试将数据帧写入 MySQL 表,但出现(111 Connection refused)
错误。
I followed the accepted answer here: Writing to MySQL database with pandas using SQLAlchemy, to_sql
我按照这里接受的答案进行操作: 使用 SQLAlchemy, to_sql 使用 Pandas 写入 MySQL 数据库
Answer's code:
答案的代码:
import pandas as pd
import mysql.connector
from sqlalchemy import create_engine
engine = create_engine('mysql+mysqlconnector://[user]:[pass]@[host]:[port]/[schema]', echo=False)
data.to_sql(name='sample_table2', con=engine, if_exists = 'append', index=False)
...and the create_engine()
line worked without error, but the to_sql()
line failed with this error:
...并且该create_engine()
行没有错误地工作,但该to_sql()
行因此错误而失败:
(mysql.connector.errors.InterfaceError) 2003: Can't connect to MySQL server on 'localhost:3306' (111 Connection refused)
How I connect to my MySQL database / table is not really relevant, so completely different answers are appreciated, but given the deprecation of the MySQL 'flavor' in pandas 0.20.2, what is the proper way to write a dataframe to MySQL?
我如何连接到我的 MySQL 数据库/表并不是真正相关的,所以完全不同的答案值得赞赏,但鉴于Pandas 0.20.2 中 MySQL 'flavor'的弃用,将数据帧写入 MySQL 的正确方法是什么?
回答by elPastor
Thanks to a tip from @AndyHayden, this answerwas the trick. Basically replacing mysqlconnector
with mysqldb
was the linchpin.
感谢@AndyHayden 的提示,这个答案就是诀窍。基本上取代mysqlconnector
的mysqldb
是关键。
engine = create_engine('mysql+mysqldb://[user]:[pass]@[host]:[port]/[schema]', echo = False)
df.to_sql(name = 'my_table', con = engine, if_exists = 'append', index = False)
Where [schema]
is the database name, and in my particular case, :[port]
is omitted with [host]
being localhost
.
哪里[schema]
是数据库名称,并在我的具体情况,:[port]
省略与[host]
是localhost
。