Python:受cursor.execute(“SELECT ...)影响的行数
如何访问受以下因素影响的行数:
cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'")
How can I access the number of rows affected by:
cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
尝试使用
fetchone
:result
将保存一个包含一个元素的元组,即COUNT(*)
的值。因此,要找到行数:
或者,如果您想一次性完成:
PS。尽可能使用参数化参数也是一种很好的做法,因为它可以在需要时自动为您引用参数,并防止 SQL 注入。
参数化参数的正确语法取决于您的 python/数据库适配器(例如 mysqldb、psycopg2 或 sqlite3)。它看起来像
Try using
fetchone
:result
will hold a tuple with one element, the value ofCOUNT(*)
.So to find the number of rows:
Or, if you'd rather do it in one fell swoop:
PS. It's also good practice to use parametrized arguments whenever possible, because it can automatically quote arguments for you when needed, and protect against sql injection.
The correct syntax for parametrized arguments depends on your python/database adapter (e.g. mysqldb, psycopg2 or sqlite3). It would look something like
来自PEP 249,通常由Python数据库API实现:
[...]
但要小心——它接着说:
因此,如果您执行了语句,并且它有效,并且您确定您的代码将始终针对同一 DBMS 的同一版本运行,这是一个合理的解决方案。
From PEP 249, which is usually implemented by Python database APIs:
[…]
But be careful—it goes on to say:
So if you've executed your statement, and it works, and you're certain your code will always be run against the same version of the same DBMS, this is a reasonable solution.
受影响的行数是从execute返回的:
当然,正如AndiDog已经提到的,您可以随时通过访问游标的rowcount属性来获取行数,以获取最后一次执行的计数:
来自python的内联文档MySQL数据库:
The number of rows effected is returned from execute:
of course, as AndiDog already mentioned, you can get the row count by accessing the rowcount property of the cursor at any time to get the count for the last execute:
From the inline documentation of python MySQLdb:
在我看来,获取所选行数的最简单方法如下:
使用 fetch 命令(fetchall()、fetchone()、fetchmany())时,游标对象返回一个包含结果的列表。要获取选定的行,只需打印此列表的长度即可。但这对于 fetchall() 来说才有意义。 ;-)
In my opinion, the simplest way to get the amount of selected rows is the following:
The cursor object returns a list with the results when using the fetch commands (fetchall(), fetchone(), fetchmany()). To get the selected rows just print the length of this list. But it just makes sense for fetchall(). ;-)
为了获取所选行的数量,我通常使用以下命令:
To get the number of selected rows I usually use the following:
使用
count(*)
时,结果为{'count(*)': 9}
—— 例如,其中 9 代表表中的行数。
因此,为了获取正确的数字,这在我的例子中是有效的,使用 mysql 8。
when using
count(*)
the result is{'count(*)': 9}
-- where 9 represents the number of rows in the table, for the instance.
So, in order to fetch the just the number, this worked in my case, using mysql 8.
接受的答案很好,但执行光标后如何在一行中获取它:
result = cur.fetchone()[0]
The accepted answer is fine, but here's how you can get it in one line after executing the cursor:
result = cur.fetchone()[0]