Pandas 0.20.2 to_sql()使用MySQL

2024-05-08 11:46:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图将数据帧写入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写入数据帧的正确方法是什么?


Tags: to数据答案importfalsepandassqlconnector
1条回答
网友
1楼 · 发布于 2024-05-08 11:46:02

多亏了@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

相关问题 更多 >