【问题标题】:Pandas 0.20.2 to_sql() using MySQL使用 MySQL 的 Pandas 0.20.2 to_sql()
【发布时间】:2017-07-05 18:39:38
【问题描述】:

我正在尝试将数据帧写入 MySQL 表,但收到 (111 Connection refused) 错误。

我在这里遵循了接受的答案: Writing to MySQL database with pandas using SQLAlchemy, to_sql

答案代码:

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)

...create_engine() 行正常工作,但 to_sql() 行失败并出现此错误:

(mysql.connector.errors.InterfaceError) 2003: Can't connect to MySQL server on 'localhost:3306' (111 Connection refused)

我如何连接到我的 MySQL 数据库/表并不真正相关,因此非常感谢您提供完全不同的答案,但鉴于 deprecation of the MySQL 'flavor' in pandas 0.20.2,将数据帧写入 MySQL 的正确方法是什么?

【问题讨论】:

  • 您是否有任何其他关于连接被拒绝原因的详细信息?可能与 Python、Pandas 和 SQLAlchemy 完全无关
  • 没有其他细节 - 但是我一直使用 MySQLdb 作为我的连接器到 read_sql() 没有问题。会不会是读/写权限的区别?
  • 权限可能是它(例如,如果您只有读取权限)。您可以尝试使用其他界面(例如 MySQL Workbench 或 Sequel Pro)创建一个简单的表吗?
  • 是的,我一直在创建数据库、表、写入表等,所有这些都使用 MySQLdb... 并使用 read_sql() 读取。我有 root 访问权限,所以我应该可以写,但这可能是我设置调用的方式,以某种方式无法识别该访问权限。
  • @openwon - 毕竟,我意识到to_sql() 对于任何相关大小的数据集来说有多慢,我正在追逐LOAD DATA INFILE 方法...

标签: python mysql pandas pandas-to-sql


【解决方案1】:

感谢@AndyHayden 的提示,this answer 是诀窍。基本上用mysqldb 替换mysqlconnector 是关键。

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)

[schema] 是数据库名称,在我的特定情况下,:[port] 被省略,[host]localhost

【讨论】:

  • 把它放在这里以便其他人可以避免:在@elPastor answer engine = create_engine('mysql+mysqldb://root:password@localhost:3306/mydbname', echo = False)跨度>
猜你喜欢
  • 2015-08-18
  • 1970-01-01
  • 2016-01-31
  • 2021-01-25
  • 2019-04-21
  • 1970-01-01
  • 2019-07-05
  • 2018-04-09
  • 2017-05-24
相关资源
最近更新 更多