python 属性错误:使用www.example.com_sql()时,"连接"对象没有属性"连接"df.to_sql()

b5lpy0ml  于 2023-02-02  发布在  Python
关注(0)|答案(1)|浏览(169)

我尝试通过panda Dataframe 将从网站上获取的数据存储到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 EXISTSSELECT * FROM,它们都给了我想要看到的结果。

bpzcxfmw

bpzcxfmw1#

我也遇到了这个问题。Pandas 1.x doesn't support SqlAlchemy 2 yetAs the relevant Github issue shows下一个版本的Pandas将需要sqlalchemy<2.0。现在你必须降级到SqlAlchemy 1.4.x,例如:

pip install --upgrade SQLAlchemy==1.4.46

这个问题是由Pandas版本和SqlAlchemy 2.0之间的不兼容引起的。SqlAlchemy 2.0是released on January 28, 2023,而即使是当时最新的Pandas版本1.5.3也是在1月19日发布的。
Pandas * 不 * 支持sqlalchemy.engine.Connection。从the docs

cons:qlalchemy.engine(引擎或连接)或sqlite3.连接

使用SQLAlchemy可以使用该库支持的任何数据库。为sqlite3.Connection对象提供了传统支持。用户负责SQLAlchemy可连接的引擎处置和连接关闭请参见here
我降级到SqlAlchemy 1.4.46,to_sql不再抱怨。
如果使用pip,则可以使用以下命令降级:

pip install --upgrade SQLAlchemy==1.4.46

pip install SQLAlchemy
pip install SQLAlchemy==1.4.46

相关问题