简体   繁体   English

熊猫 0.20.2 to_sql() 使用 MySQL

[英]Pandas 0.20.2 to_sql() using MySQL

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我在这里遵循了公认的答案: Writing to MySQL database with pandas using SQLAlchemy, to_sql

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 的正确方法是什么?

Thanks to a tip from @AndyHayden, this answer was the trick.感谢@AndyHayden 的提示,这个答案就是诀窍。 Basically replacing mysqlconnector with mysqldb was the linchpin.基本上用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM