Python的:受cursor.execute行数(“SELECT ...)
题
如何访问受行数:
cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'")
解决方案
尝试使用fetchone
:
cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'")
result=cursor.fetchone()
result
将举行一个元组与一个元件,COUNT(*)
的值。
因此,要找到行数:
number_of_rows=result[0]
或者,如果你宁愿做一举:
cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'")
(number_of_rows,)=cursor.fetchone()
PS。它也使用参数化的参数只要有可能,因为在需要时它可以自动报价参数为你,并防止SQL注入的良好做法。
为参数化的自变量的正确语法取决于你的Python /数据库适配器上(例如MySQLdb的,psycopg2或sqlite3的)。它看起来像
cursor.execute("SELECT COUNT(*) from result where server_state= %s AND name LIKE %s",[2,digest+"_"+charset+"_%"])
(number_of_rows,)=cursor.fetchone()
其他提示
从 PEP 249 时,这通常是由Python的数据库API实现:
游标对象应当通过以下方法响应和属性:
[...]
的
.rowcount
强>
此只读属性指定的行的最后一个.execute *()中产生(对于DQL语句如“选择”)或影响(DML语句如“更新”或“插入件”)的数量。
但要小心,它接着说:
在属性是-1的情况下,没有
.execute*()
具有上的光标被执行或最后一个操作的行数是不能由接口来确定。 [7]注意:强>结果 数据库API规范的未来版本可以重新定义后一种情况下以具有对象返回
None
而不是-1。
所以,如果你执行你的语句中,和的它的工作原理,和的你肯定你的代码将永远对同一版本的同一DBMS的运行,这是合理的解决方案。
从执行返回受影响的行数:
rows_affected=cursor.execute("SELECT ... ")
当然,作为AndiDog已经提到的,你可以在任何时间访问光标的行数属性来获取行计数得到计数最后执行:
cursor.execute("SELECT ... ")
rows_affected=cursor.rowcount
从蟒MySQLdb的的内联文档:
def execute(self, query, args=None):
"""Execute a query.
query -- string, query to execute on server
args -- optional sequence or mapping, parameters to use with query.
Note: If args is a sequence, then %s must be used as the
parameter placeholder in the query. If a mapping is used,
%(key)s must be used as the placeholder.
Returns long integer rows affected, if any
"""
在我的意见,为了得到选定行的量的最简单的方法如下:
使用取命令时的光标对象返回的结果的列表(使用fetchall(),fetchone(),支持fetchmany())。要获得所选行只打印此列表的长度。但它只是有意义的使用fetchall()。 ; - )
示例:
print len(cursor.fetchall)