使用 SQLAlchemy、to_sql 用 Pandas 写入 MySQL 数据库

Writing to MySQL database with pandas using SQLAlchemy, to_sql(使用 SQLAlchemy、to_sql 用 Pandas 写入 MySQL 数据库)
本文介绍了使用 SQLAlchemy、to_sql 用 Pandas 写入 MySQL 数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用 to_sql 将 pandas 数据帧写入 MySQL 表.之前一直在使用 flavor='mysql',但是将来会折旧,并希望开始过渡到使用 SQLAlchemy 引擎.

trying to write pandas dataframe to MySQL table using to_sql. Previously been using flavor='mysql', however it will be depreciated in the future and wanted to start the transition to using SQLAlchemy engine.

示例代码:

import pandas as pd
import mysql.connector
from sqlalchemy import create_engine

engine = create_engine('mysql+mysqlconnector://[user]:[pass]@[host]:[port]/[schema]', echo=False)
cnx = engine.raw_connection()
data = pd.read_sql('SELECT * FROM sample_table', cnx)
data.to_sql(name='sample_table2', con=cnx, if_exists = 'append', index=False)

读取工作正常,但 to_sql 有错误:

The read works fine but the to_sql has an error:

DatabaseError: sql 'SELECT name FROM sqlite_master 执行失败WHERE type='table' AND name=?;': 期间的参数数量错误字符串格式化

DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': Wrong number of arguments during string formatting

为什么看起来像是在尝试使用sqlite?sqlalchemy 与 mysql 的连接的正确用法是什么,特别是 mysql.connector?

Why does it look like it is trying to use sqlite? What is the correct use of a sqlalchemy connection with mysql and specifically mysql.connector?

我也尝试将引擎作为连接传入,这给了我一个没有引用游标对象的错误.

I also tried passing the engine in as the connection as well, and that gave me an error referencing no cursor object.

data.to_sql(name='sample_table2', con=engine, if_exists = 'append', index=False)
>>AttributeError: 'Engine' object has no attribute 'cursor'

推荐答案

使用引擎代替 raw_connection() 工作:

Using the engine in place of the raw_connection() worked:

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)

不清楚为什么我昨天尝试这个时它给了我之前的错误.

Not clear on why when I tried this yesterday it gave me the earlier error.

这篇关于使用 SQLAlchemy、to_sql 用 Pandas 写入 MySQL 数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)