0

我在一个Ubuntu 22.04带有Python 3.10.

我使用这些 apt 包:

mysql-client
libmysqlclient-dev

我使用以下 Python 包:

import mysqlclient==2.1.0
import sqlalchemy
# for the environment variables:
from dotenv import load_dotenv
# And to use sessions with flush, with the commit only at the end:
from sqlalchemy.orm import sessionmaker

sessionmaker参数autoflush设置为 True。

我想添加一个删除,然后插入一个 sqlalchemy.orm 会话,这样我只在两个命令运行良好时才提交。这样做的目的是更新在一天中更新的表。在不确定插入是否真的有效之前,我不想删除任何内容。

导致此错误的Python代码部分(没有后续插入命令):

DELETE_QUERY = f"""
    DELETE FROM {MY_TABLE} 
    WHERE checkdate = DATE(NOW())
"""

def delete_execute(sess, conn, query):
    """Function for deleting and adding to sess values 
    from the DB
    :param connection: pymsql connection to DB
    :param query: SQL query containing DELETE keyword
    :return: count of rows deleted
    """
    try:
        cursor = conn.cursor()
        sess.add(cursor.execute(query))
        # # Not yet commit, only after insertion:
        # connection.commit()
        # # Updates the objects of the session:
        # sess.flush()
        # # Not needed here since autoflush is set to True
        return cursor.rowcount, sess

engine = create_engine(CONNECTION)
# Session = sessionmaker(engine)
Session = sessionmaker(autocommit=False, autoflush=True, bind=engine)

# Connect to DB
logging.info("Connecting to DB ...")

# # with statement closes the connection automatically,
# # see https://docs.sqlalchemy.org/en/14/dialects/mysql.html
# # But the class does not have the needed __enter__ attribute
# https://stackoverflow.com/questions/51427729/python-error-attributeerror-enter
# with engine.connect() as conn:
# # engine.connect() throws an error as well:
# conn = engine.connect() 
# # connection.cursor() AttributeError: 'Connection' object has no attribute 'cursor'
# https://stackoverflow.com/questions/38332787/pandas-to-sql-to-sqlite-returns-engine-object-has-no-attribute-cursor
conn = engine.raw_connection()

with Session() as sess:
    # The records only get deleted after commit
    # This only adds them to the session.
    deleted_records_count, sess = delete_execute(sess, conn, DELETE_QUERY)

我没有从其他链接中获得相同错误的线索:

用户模型包含许多任务模型,任务模型包含许多子任务模型。

...使用 SQLAlchemy 和 Marshmallow 将新用户插入数据库。

我是 sqlalchemy.orm 的新手,我担心我误解了一些东西。我想使用会话来删除并随后插入记录,并且我只想在两个命令的末尾提交。我使用光标进行删除。我如何嵌入光标 - 只能通过conn对象使用conn = engine.raw_connection()- 以便只有在下一个插入任务也有效时才能完成任务?我不能只将它添加到会话中:

sess.add(cursor.execute(query))

哪个抛出:

sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.int' is not mapped

详细错误:

Traceback (most recent call last):
  File "/usr/lib/python3.9/runpy.py", line 197, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/usr/lib/python3.9/runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "/MY_PROJECT/main.py", line 574, in <module>
    get_sql_and_save_as_csv_in_gcs(request)
  File "/MY_PROJECT/main.py", line 489, in get_sql_and_save_as_csv_in_gcs
    deleted_records_count, sess = delete_execute(sess, conn, DELETE_QUERY)
  File "/usr/local/lib/python3.9/dist-packages/dryable/__init__.py", line 34, in _decorated
    return function( * args, ** kwargs )
  File "/MY_PROJECT/main.py", line 204, in delete_execute
    sess.add(cursor.execute(query))
  File "/usr/local/lib/python3.9/dist-packages/sqlalchemy/orm/session.py", line 2601, in add
    util.raise_(
  File "/usr/local/lib/python3.9/dist-packages/sqlalchemy/util/compat.py", line 207, in raise_
    raise exception
sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.int' is not mapped

那么我该怎么做呢?

4

1 回答 1

1
from sqlalchemy.sql import func

with Session() as session:
    # Model here is the orm Model, you could also do something similar
    # using sqlalchemy's core layer.
    cursor_result = session.query(Model).filter(Model.checkdate == func.now()).delete()
    deleted_rowcount = cursor_result.rowcount
    # This will insert each model at a time, maybe you want to do something
    # with better performance here.
    session.add_all(new_models)
    # commit delete and perform inserts
    session.commit()

事实证明,使用上面的 orm delete 返回一个游标,您可以在此处阅读:update-and-delete-with-arbitrary-where-clause

使用表对象的核心版本应该可以使用session.execute,您可以在此处阅读:getting-affected-row-count-from-update-delete

于 2022-01-31T05:20:12.270 回答