SQLAlchemy 2.0 锁定表选项?

问题描述 投票:0回答:1

SQLAlchemy 2.0 有任何选项来执行

LOCK TABLE table_name
sql 查询吗? 似乎 SQLAlchemy 文档缺少这些信息。

作为一个例子,我想执行

create_engine().connect().execute(text("LOCK TABLE table_name"))
create_engine().connect().execute(text("DELETE ..."))
create_engine().connect().execute(text("INSERT ..."))
create_engine().connect().commit()
python python-3.x postgresql sqlalchemy locking
1个回答
0
投票

SQLAlchemy 2.0 没有内置选项来执行 LOCK TABLE 语句。但是,您可以使用 raw() 方法执行任何原始 SQL 查询,包括 LOCK TABLE。

from sqlalchemy import create_engine, text

engine = create_engine('postgresql://localhost:5432/my_database')

connection = engine.connect()

# Lock the table
connection.execute(text("LOCK TABLE table_name"))

# Delete all rows from the table
connection.execute(text("DELETE FROM table_name"))

# Insert a new row into the table
connection.execute(text("INSERT INTO table_name (name) VALUES ('New row')"))

# Commit the changes
connection.commit()

# Close the connection
connection.close()

需要注意的是,如果不小心的话,使用 raw() 方法可能会很危险。确保在执行 SQL 查询之前对其进行验证,并避免使用它来执行动态 SQL 查询。如果需要定期锁定表,建议使用特定于数据库的锁定机制。例如,PostgreSQL 有一个内置的锁定机制,您可以在对表执行操作之前使用它来锁定表。

© www.soinside.com 2019 - 2024. All rights reserved.