我正在尝试通过pandas数据框将从网站检索到的数据存储到MySQL数据库中。然而,当我调用
df.to_sql()
函数时,编译器会给我一个错误消息,说:AttributeError: 'Connection' object has no attribute 'connect'
。我测试了几次,确信既没有连接问题也没有表存在问题。代码本身有什么问题吗?我使用的代码如下: from sqlalchemy import create_engine, text
import pandas as pd
import mysql.connector
config = configparser.ConfigParser()
config.read('db_init.INI')
password = config.get("section_a", "Password")
host = config.get("section_a", "Port")
database = config.get("section_a", "Database")
engine = create_engine('mysql+mysqlconnector://root:{0}@{1}/{2}'.
format(password, host, database),
pool_recycle=1, pool_timeout=57600, future=True)
conn = engine.connect()
df.to_sql("tableName", conn, if_exists='append', index = False)
完整的堆栈跟踪如下:
Traceback (most recent call last):
File "/Users/chent/Desktop/PFSDataParser/src/FetchPFS.py", line 304, in <module>
main()
File "/Users/chent/Desktop/PFSDataParser/src/FetchPFS.py", line 287, in main
insert_to_db(experimentDataSet, expName)
File "/Users/chent/Desktop/PFSDataParser/src/FetchPFS.py", line 89, in insert_to_db
df.to_sql(tableName, conn, if_exists='append', index = False)
File "/Users/chent/opt/anaconda3/lib/python3.9/site-packages/pandas/core/generic.py", line 2951, in to_sql
return sql.to_sql(
File "/Users/chent/opt/anaconda3/lib/python3.9/site-packages/pandas/io/sql.py", line 698, in to_sql
return pandas_sql.to_sql(
File "/Users/chent/opt/anaconda3/lib/python3.9/site-packages/pandas/io/sql.py", line 1754, in to_sql
self.check_case_sensitive(name=name, schema=schema)
File "/Users/chent/opt/anaconda3/lib/python3.9/site-packages/pandas/io/sql.py", line 1647, in check_case_sensitive
with self.connectable.connect() as conn:
AttributeError: 'Connection' object has no attribute 'connect'
我使用的pandas版本是1.4.4,sqlalchemy是2.0
我尝试执行了几个SQL查询,例如CREATE TABLE xxx IF NOT EXISTS
或SELECT * FROM
,所有这些都给了我想要看到的结果。
conn = engine.connect()
,并将另一行改为df.to_sql("tableName", engine, if_exists='append', index = False)
。 - nacho