【问题标题】:Select query in pymysql在pymysql中选择查询
【发布时间】:2015-04-16 07:39:59
【问题描述】:

执行以下操作时:

import pymysql 



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

输出为1

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

我确信答案很简单,但我是初学者,因此非常感谢任何帮助 - 谢谢!

【问题讨论】:

    标签: python sql pymysql


    【解决方案1】:

    cur.execute() 只返回受影响的行数。您应该使用cur.fetchone() 来获得实际结果,或者如果您需要多行,则应该使用cur.fetchall()

    【讨论】:

      【解决方案2】:

      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'])
      

      祝你好运!

      【讨论】:

      • cur.execute(sql, UserId)cur.execute(sql % UserId) 更好,因为您正在利用函数来清理输入,而不仅仅是使用 python 字符串格式。
      猜你喜欢
      • 2014-08-07
      • 1970-01-01
      • 2021-09-22
      • 2016-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-13
      • 2020-09-03
      相关资源
      最近更新 更多