Python:受cursor.execute(“SELECT ...)影响的行数

发布于 2024-08-26 14:59:13 字数 158 浏览 3 评论 0原文

如何访问受以下因素影响的行数:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

七秒鱼° 2024-09-02 14:59:13

尝试使用 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()

Try using fetchone:

cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'")
result=cursor.fetchone()

result will hold a tuple with one element, the value of COUNT(*).
So to find the number of rows:

number_of_rows=result[0]

Or, if you'd rather do it in one fell swoop:

cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'")
(number_of_rows,)=cursor.fetchone()

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

cursor.execute("SELECT COUNT(*) from result where server_state= %s AND name LIKE %s",[2,digest+"_"+charset+"_%"])
(number_of_rows,)=cursor.fetchone()
时光瘦了 2024-09-02 14:59:13

来自PEP 249,通常由Python数据库API实现:

光标对象应响应以下方法和属性:

[...]

.rowcount
此只读属性指定最后一个 .execute*() 生成的行数(对于“select”等 DQL 语句)或受影响的行数(对于“update”或“insert”等 DML 语句)。

但要小心——它接着说:

如果没有 .execute*( ) 已经对游标执行过或者接口无法确定最后一次操作的行数。 [7]

注意:
DB API 规范的未来版本可能会重新定义后一种情况,让对象返回 None 而不是 -1。

因此,如果您执行了语句,并且它有效,并且您确定您的代码将始终针对同一 DBMS 的同一版本运行,这是一个合理的解决方案。

From PEP 249, which is usually implemented by Python database APIs:

Cursor Objects should respond to the following methods and attributes:

[…]

.rowcount
This read-only attribute specifies the number of rows that the last .execute*() produced (for DQL statements like 'select') or affected (for DML statements like 'update' or 'insert').

But be careful—it goes on to say:

The attribute is -1 in case no .execute*() has been performed on the cursor or the rowcount of the last operation is cannot be determined by the interface. [7]

Note:
Future versions of the DB API specification could redefine the latter case to have the object return None instead of -1.

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.

泪是无色的血 2024-09-02 14:59:13

受影响的行数是从execute返回的:

rows_affected=cursor.execute("SELECT ... ")

当然,正如AndiDog已经提到的,您可以随时通过访问游标的rowcount属性来获取行数,以获取最后一次执行的计数:

cursor.execute("SELECT ... ")
rows_affected=cursor.rowcount

来自python的内联文档MySQL数据库:

 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

    """

The number of rows effected is returned from execute:

rows_affected=cursor.execute("SELECT ... ")

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:

cursor.execute("SELECT ... ")
rows_affected=cursor.rowcount

From the inline documentation of python 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

    """
仅此而已 2024-09-02 14:59:13

在我看来,获取所选行数的最简单方法如下:

使用 fetch 命令(fetchall()、fetchone()、fetchmany())时,游标对象返回一个包含结果的列表。要获取选定的行,只需打印此列表的长度即可。但这对于 fetchall() 来说才有意义。 ;-)

print len(cursor.fetchall)

# python3
print(len(cur.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(). ;-)

print len(cursor.fetchall)

# python3
print(len(cur.fetchall()))
人疚 2024-09-02 14:59:13

为了获取所选行的数量,我通常使用以下命令:

cursor.execute(sql)
count = len(cursor.fetchall())

To get the number of selected rows I usually use the following:

cursor.execute(sql)
count = len(cursor.fetchall())
甜尕妞 2024-09-02 14:59:13

使用 count(*) 时,结果为 {'count(*)': 9}

—— 例如,其中 9 代表表中的行数。

因此,为了获取正确的数字,这在我的例子中是有效的,使用 mysql 8。

cursor.fetchone()['count(*)']

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.

cursor.fetchone()['count(*)']
人海汹涌 2024-09-02 14:59:13

接受的答案很好,但执行光标后如何在一行中获取它:

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]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文