Использование операторов UPDATE и DELETE

Select Update Delete ,

Конструкция SQL-выражения update()

В качестве источника питания используется update() f Update u

insert() update() L

Базовый UPDATE выглядит следующим образом:

>>> from sqlalchemy import update
>>> stmt = (
...     update(user_table)
...     .where(user_table.c.name == "patrick")
...     .values(fullname="Patrick the Star")
... )
>>> print(stmt)
{printsql}UPDATE user_account SET fullname=:fullname WHERE user_account.name = :name_1

Встретились <<<0>> Insert >

:class:`_schema.Column`U

>>> stmt = update(user_table).values(fullname="Username: " + user_table.c.name)
>>> print(stmt)
{printsql}UPDATE user_account SET fullname=(:name_1 || user_account.name)

:func:`_sql.bindparam`К с

>>> from sqlalchemy import bindparam
>>> stmt = (
...     update(user_table)
...     .where(user_table.c.name == bindparam("oldname"))
...     .values(name=bindparam("newname"))
... )
>>> with engine.begin() as conn:
...     conn.execute(
...         stmt,
...         [
...             {"oldname": "jack", "newname": "ed"},
...             {"oldname": "wendy", "newname": "mary"},
...             {"oldname": "jim", "newname": "jake"},
...         ],
...     )
{execsql}BEGIN (implicit)
UPDATE user_account SET name=? WHERE user_account.name = ?
[...] [('ed', 'jack'), ('mary', 'wendy'), ('jake', 'jim')]
<sqlalchemy.engine.cursor.CursorResult object at 0x...>
COMMIT{stop}

Другие методы, которые могут быть применены к UPDATE, включают в себя:

Корреляционные обновления

:ref:`correlated subquery <tutorial_scalar_subquery>`An

>>> scalar_subq = (
...     select(address_table.c.email_address)
...     .where(address_table.c.user_id == user_table.c.id)
...     .order_by(address_table.c.id)
...     .limit(1)
...     .scalar_subquery()
... )
>>> update_stmt = update(user_table).values(fullname=scalar_subq)
>>> print(update_stmt)
{printsql}UPDATE user_account SET fullname=(SELECT address.email_address
FROM address
WHERE address.user_id = user_account.id ORDER BY address.id
LIMIT :param_1)

UPDATE…FROM

Некоторые

>>> update_stmt = (
...     update(user_table)
...     .where(user_table.c.id == address_table.c.user_id)
...     .where(address_table.c.email_address == "patrick@aol.com")
...     .values(fullname="Pat")
... )
>>> print(update_stmt)
{printsql}UPDATE user_account SET fullname=:fullname FROM address
WHERE user_account.id = address.user_id AND address.email_address = :email_address_1

:class:`_schema.Table`Ther

>>> update_stmt = (
...     update(user_table)
...     .where(user_table.c.id == address_table.c.user_id)
...     .where(address_table.c.email_address == "patrick@aol.com")
...     .values(
...         {
...             user_table.c.fullname: "Pat",
...             address_table.c.email_address: "pat@aol.com",
...         }
...     )
... )
>>> from sqlalchemy.dialects import mysql
>>> print(update_stmt.compile(dialect=mysql.dialect()))
{printsql}UPDATE user_account, address
SET address.email_address=%s, user_account.fullname=%s
WHERE user_account.id = address.user_id AND address.email_address = %s

Упорядоченные по параметрам обновления

:meth:`_sql.Update.ordered_values`Ano

>>> update_stmt = update(some_table).ordered_values(
...     (some_table.c.y, 20), (some_table.c.x, some_table.c.y + 10)
... )
>>> print(update_stmt)
{printsql}UPDATE some_table SET y=:y, x=(some_table.y + :y_1)

Конструкция SQL-выражения delete()

В качестве источника питания используется delete() f Delete u

В качестве источника информации используется <<<0>> update() >

>>> from sqlalchemy import delete
>>> stmt = delete(user_table).where(user_table.c.name == "patrick")
>>> print(stmt)
{printsql}DELETE FROM user_account WHERE user_account.name = :name_1

Удаление нескольких таблиц

Update Delete DELETE FROM..USING L

>>> delete_stmt = (
...     delete(user_table)
...     .where(user_table.c.id == address_table.c.user_id)
...     .where(address_table.c.email_address == "patrick@aol.com")
... )
>>> from sqlalchemy.dialects import mysql
>>> print(delete_stmt.compile(dialect=mysql.dialect()))
{printsql}DELETE FROM user_account USING user_account, address
WHERE user_account.id = address.user_id AND address.email_address = %s

Получение количества затронутых строк из UPDATE, DELETE

Update Delete Connection Connection.execute() CursorResult.rowcount G

>>> with engine.begin() as conn:
...     result = conn.execute(
...         update(user_table)
...         .values(fullname="Patrick McStar")
...         .where(user_table.c.name == "patrick")
...     )
...     print(result.rowcount)
{execsql}BEGIN (implicit)
UPDATE user_account SET fullname=? WHERE user_account.name = ?
[...] ('Patrick McStar', 'patrick'){stop}
1
{execsql}COMMIT{stop}

Совет

Клавиша <<<0>> Result cursor Connection.execute() Session.execute() >

:attr:`_engine.CursorResult.rowcount`F

  • Возвращаемое значение - это количество строк, сопоставленных предложением WHERE оператора. При этом не имеет значения, был ли ряд действительно изменен или нет.

  • CursorResult.rowcount

  • executemany <tutorial_multiple_parameters>`F :attr:`_engine.CursorResult.rowcount CursorResult.supports_sane_multi_rowcount o

  • CursorResult.supports_sane_rowcount е

  • unit of work`Некоторы :ref:`mapper_version_counter е

Использование RETURNING с UPDATE, DELETE

Insert Update Delete Update.returning() Delete.returning() Result L

>>> update_stmt = (
...     update(user_table)
...     .where(user_table.c.name == "patrick")
...     .values(fullname="Patrick the Star")
...     .returning(user_table.c.id, user_table.c.name)
... )
>>> print(update_stmt)
{printsql}UPDATE user_account SET fullname=:fullname
WHERE user_account.name = :name_1
RETURNING user_account.id, user_account.name{stop}

>>> delete_stmt = (
...     delete(user_table)
...     .where(user_table.c.name == "patrick")
...     .returning(user_table.c.id, user_table.c.name)
... )
>>> print(delete_stmt)
{printsql}DELETE FROM user_account
WHERE user_account.name = :name_1
RETURNING user_account.id, user_account.name{stop}

Дополнительная литература по UPDATE, DELETE

См.также

Документация по API для UPDATE / DELETE:

UPDATE и DELETE с поддержкой ORM:

Операции INSERT, UPDATE и DELETE с поддержкой ORM - Руководство по составлению запросов в ORM в

Вернуться на верх