在pymysql中选择查询

Jas*_*078 11 python sql pymysql

执行以下操作时:

import pymysql 



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

输出是1

我怎么能改变代码,以便打印ParentGuardianID(即'001')的实际值而不是1.

我确信答案很简单,但我是初学者,所以任何帮助都会非常感激 - 谢谢!

Dan*_*man 20

cur.execute()只返回受影响的行数.你应该做的cur.fetchone()是获得实际的结果,或者cur.fetchall()你期望多行.


小智 19

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'])
Run Code Online (Sandbox Code Playgroud)

祝好运!