sqlalchemy - 如何获得更新方法结果?

kkk*_*kv_ 5 sqlalchemy

我执行update方法:

# connect db to get `conn`
# get metadate which is table `account`
u = account.update().where(account.c.ID == 9).values(USERNAME='k9')
r = conn.execute(u)
Run Code Online (Sandbox Code Playgroud)

我怎样才能获得update成功或失败?我检查了文档,但没有找到...

或者也许我只是不在乎这个?

r是一个ResultProxy自动update提交和关闭的操作。

谢谢:)


附加

谢谢@Lucas Kahlert 的回答,好点!

rowcount满足我的问题的情况。

文档行数

This attribute returns the number of rows matched, 
which is not necessarily the same as the number of rows that were actually modified

In [7]: u = account.update().\
        where( and_((account.c.ID == 4), (account.c.PWD =='4297f44b1'))).\
        values(PWD='hahahaha')

In [8]: print u
UPDATE `ACCOUNT` SET `PWD`=%s WHERE `ACCOUNT`.`ID` = %s AND `ACCOUNT`.`PWD` = %s

In [11]: rst = conn.execute(u)

In [12]: rst.rowcount  # found row and did update action
Out[12]: 1L

In [13]: rst = conn.execute(u)

In [14]: rst.rowcount  # found row but value is same, so do not do update action
Out[14]: 0L
Run Code Online (Sandbox Code Playgroud)

Luc*_*ert 6

rowcount您可以使用 的属性检查查询影响了多少行ResultProxy。告诉rowcount您有多少行符合您的WHERE条件。这与受影响的行不同(请参阅此问题),但应该适合您的情况。

没有行受到影响

UPDATE如果没有行与您的条件匹配,则无论语句中的数据是否正确,都会执行查询。

违反约束

如果行匹配并且您尝试使用无效的数据集更新行,SQLAlchemy 将引发约束冲突异常(例如sqlalchemy.exc.IntegrityError)。在这种情况下,您可以捕获异常并将其用于“成功”检查。

如果在您的 期间没有发生约束违规UPDATE,则该语句会默默地成功。

from sqlalchemy import create_engine
from sqlalchemy import Column, MetaData, Table
from sqlalchemy import Integer, String, ForeignKey
from sqlalchemy.orm import mapper, sessionmaker

class User(object):
    def __repr__(self):
        return "<User('%s','%s', '%s')>" % (self.name, self.fullname, self.password)

# create a connection to a in-memory sqlite database
# turn echo on to see the auto-generated SQL
engine = create_engine("sqlite://", echo=True)

# this is used to keep track of tables and their attributes
metadata = MetaData()
account = Table('account', metadata,
                Column('ID', Integer, primary_key=True),
                Column('USERNAME', String, unique=True))

# create the table and tell it to create it in the  database engine that is
# passed
metadata.create_all(engine)

# create a mapping between the account and the User class
mapper(User, account)

# populate database
engine.execute(account.insert().values(ID=9,  USERNAME='account-9'))
engine.execute(account.insert().values(ID=10, USERNAME='account-10'))

result = engine.execute(account.update().where(account.c.ID==9).values(USERNAME='k9'))
print('Matched rows:', result.rowcount) # 1

# This query will succeed, because there is not row with ID 20. It does not
# matter, if the USERNAME 'k9' is invalid (because there is already a 'k9')
result = engine.execute(account.update().where(account.c.ID==20).values(USERNAME='k9'))
print('Matched rows:', result.rowcount) # 0


# Constraint violation
# 
# will raise an:
#   sqlalchemy.exc.IntegrityError:
#       (IntegrityError) UNIQUE constraint failed: account.USERNAME
#       'UPDATE account SET "USERNAME"=? WHERE account."ID" = ?' ('k9', 10)
result = engine.execute(account.update().where(account.c.ID==10).values(USERNAME='k9'))
Run Code Online (Sandbox Code Playgroud)