Python 如何从 psycopg2 connection.commit() 获得受影响的行数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24441132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get affected row count from psycopg2 connection.commit()?
提问by amphibient
Currently, I have the following method to execute INSERT/UPDATE/DELETE statements using psycopg2
in Python
:
目前,我有以下方法使用psycopg2
in执行 INSERT/UPDATE/DELETE 语句Python
:
def exec_statement(_cxn, _stmt):
try:
db_crsr = _cxn.cursor()
db_crsr.execute(_stmt)
_cxn.commit()
db_crsr.close()
return True
except:
return False
But what I would really like it to do, instead of bool, is return the row count affected by the transaction or -1 if the operation fails.
但我真正希望它做的不是 bool,而是返回受事务影响的行数,如果操作失败则返回 -1。
Is there a way to get a number of rows affected by _cxn.commit()
? E.g. for a single INSERT it would be always 1, for a DELETE or UPDATE, the number of rows affected by the statement etc.?
有没有办法获得受 影响的行数_cxn.commit()
?例如,对于单个 INSERT,它始终为 1,对于 DELETE 或 UPDATE,受语句影响的行数等。?
采纳答案by khampson
commit()
can't be used to get the row count, but you can use the cursor
to get that information after each execute
call. You can use its rowcount
attribute to get the number of rows affected for SELECT
, INSERT
, UPDATE
and DELETE
.
commit()
不能用于获取行数,但您可以cursor
在每次execute
调用后使用获取该信息。您可以使用它的rowcount
属性来获得对受影响的行数SELECT
,INSERT
,UPDATE
和DELETE
。
i.e.
IE
db_crsr = _cxn.cursor()
db_crsr.execute(_stmt)
rowcount = db_crsr.rowcount
_cxn.commit()
db_crsr.close()
return rowcount
If you want to return the number of affected rows, I would recommend not catching any exceptions, since if the operation truly failed (say the query was malformed, or there was a FK constraint violation, etc.), an exception should be raised, and in that case the caller could catch that and behave as desired. (Or, if you want to centralize the exception handling, perhaps raise
a custom MyPostgresException
, or similar.)
如果你想返回受影响的行数,我建议不要捕获任何异常,因为如果操作真的失败(比如查询格式错误,或者存在 FK 约束违规等),应该引发异常,在这种情况下,调用者可以捕捉到它并按照需要进行操作。(或者,如果您想集中处理异常,可能raise
是 customMyPostgresException
或类似的。)
-1 can be returned in a non-failure case in certain situations (http://initd.org/psycopg/docs/cursor.html#cursor.rowcount), so I would recommend against using that value as the failure indicator. If you really want to return a numerical value in the case of failure, perhaps returning a number like -10 would work (in the except
block), since rowcount
shouldn't ever return that.
-1 在某些情况下(http://initd.org/psycopg/docs/cursor.html#cursor.rowcount)可以在非失败情况下返回,因此我建议不要使用该值作为失败指标。如果你真的想在失败的情况下返回一个数值,也许返回一个像 -10 这样的数字会起作用(在except
块中),因为rowcount
不应该返回那个。