Python 在pymysql中选择查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28530508/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:23:33  来源:igfitidea点击:

Select query in pymysql

pythonsqlpymysql

提问by Jasmine078

When executing the following:

执行以下操作时:

import pymysql 



db = pymysql.connect(host='localhost', port=3306, user='root')
cur = db.cursor()    
print(cur.execute("SELECT ParentGuardianID FROM ParentGuardianInformation WHERE UserID ='" + UserID + "'"))

The output is1

输出是1

How could I alter the code so that the actual value of the ParentGuardianID (which is '001') is printed as opposed to 1.

我如何更改代码以便打印 ParentGuardianID(即“001”)的实际值而不是1.

I'm sure the answer is simple but I am a beginner so any help would be much appreciated - thanks!

我确定答案很简单,但我是初学者,因此非常感谢您的帮助 - 谢谢!

采纳答案by Daniel Roseman

cur.execute()just returns the number of rows affected. You should do cur.fetchone()to get the actual result, or cur.fetchall()if you are expecting multiple rows.

cur.execute()只返回受影响的行数。您应该这样做cur.fetchone()以获得实际结果,或者cur.fetchall()如果您期望多行。

回答by Guillermo Luque

The cursor.execute()method gives out a cursor related to the result of the SQL sentence. In case of a selectquery, it returns the rows (if any) that meet it. So, you can iterate over these rows using a forloop for instance. In addition, I would recommend you to use pymysql.cursors.DictCursorbecause it allows treating the query results as a dictionary.

cursor.execute()方法给出与 SQL 语句结果相关的游标。在select查询的情况下,它返回满足它的行(如果有)。因此,您可以使用for循环遍历这些行。此外,我建议您使用,pymysql.cursors.DictCursor因为它允许将查询结果视为字典。

import pymysql 
db = pymysql.connect(host='localhost', port=3306, user='root')
cur = db.cursor(pymysql.cursors.DictCursor)

UserId = 'whatsoever'
sql = "SELECT ParentGuardianID FROM ParentGuardianInformation WHERE UserID ='%s'"
cur.execute(sql % UserId)
for row in cur:
    print(row['ParentGuardianID'])

Good luck!

祝你好运!