正在try 使用to_sql将pandas dataframe写入MySQL表.之前一直在使用flavor='mysql',但它将在future 贬值,并希望开始过渡到使用SQLAlchemy引擎.

示例代码:

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有一个错误:

DatabaseError:在sql"从sqlite_主机 Select 名称"上执行失败

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

我还try 将引擎作为连接传入,这给了我一个引用no cursor对象的错误.

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

推荐答案

使用发动机代替raw_connection()工作:

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)

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

Mysql相关问答推荐

在Join的ON分句中使用SUM()

—符号在哪里条件""

正则表达式转换为MYSQL格式

使用NOT EXISTS()时出现MySQL查询错误

在 MySQL 中,如何对 LIKE 查询进行批量更新,删除字符?

Group By 查询运行速度太慢而无法正常运行

MySQL 可以用于将列表排序为三分之三吗?

MySQL函数 - 如何对select查询应用多个条件

错误1075:表定义不正确;只能有一个自动列,它必须定义为一个键(使用 gorm 和 mysql)

过滤查询结果

如何将内置的时间浏览器过滤器反映到 Grafana 中的 mysql 查询中?

如何在 SQL 的计算列中显示小数点后两位?

此插页中的X是什么> X'3C2F756C3E'

MySQLi count(*) 总是返回 1

MySQL 添加一个 NOT NULL 列

授予用户对 MySQL 中有限数量表的访问权限

SQL - 如何找到列中的最高数字?

如何在特定数据库中创建表?

MySQL 实用程序 - ~/.my.cnf 选项文件

我可以在 PHP 中使用 PDO 创建数据库吗?