【问题标题】:cursor.fetchall() returns extra characters using MySQldb and pythoncursor.fetchall() 使用 MySQldb 和 python 返回额外的字符
【发布时间】:2013-01-29 10:45:34
【问题描述】:

当我使用 python 从 SQL 数据库中获取结果时,我会在返回值的开头和结尾获得额外的章程。例如下面的代码返回 ((56L,),) 而不是 56,有谁知道如何获取值...以及 (( ,),) 的实际含义...?

hp= 56
id= 3

database = MySQLdb.connect (host="localhost", user = "root", passwd = "", db = "db")

cursor = database.cursor()

cursor.execute("UPDATE period_option SET points =%s WHERE period_option_id =%s", (hp, id))

cursor.execute("SELECT points FROM period_option WHERE period_option_id =%s", (po_id_home))
results = cursor.fetchall()
print results  

【问题讨论】:

    标签: python mysql mysql-python


    【解决方案1】:

    fetchall() 返回一个元组列表(实际上是一个元组)。将其视为一系列行,其中每一行是列中的一系列项目。如果您确定您的搜索将只返回 1 行,请使用 fetchone(),它返回一个元组,它更易于解包。以下是从 fetchall() 和 fetchone() 中提取所需内容的示例:

    # Use fetchall():
    ((points,),) = cursor.fetchall()  # points = 56L
    
    # Or, if you use fetchone():
    (points,) = cursor.fetchone()     # points = 56L
    

    【讨论】:

      【解决方案2】:

      尝试以下方法,将有助于将 fetchall() 输出转换为更好的列表:

       row = cursor.fetchall()
       print row 
       output is : [(1,), (2,), (3,), (4,)]
       num = list(sum(row, ()))
       print num
       output is : [1, 2, 3, 4]
      

      【讨论】:

      • 我这样做是为了创建一个集合:fechasSet = set(sum(rows, ()))
      【解决方案3】:

      如果您使用查询只获取一个值,则可以只取第 0 个索引。

      results = cursor.fetchall()
      

      如果结果只有一个值,则使用results[0]。它应该为您提供您正在寻找的价值。 有时我们在运行查询时会得到巨大的结果,在这种情况下,我们将不得不遍历值并将其分配给列表。

      >>> result
      ('58',)
      >>> result[0]
      '58'
      

      当你对大项目运行查询时,你会在使用 curosr.fetchall() 时得到类似这样的输出

      (('58',),('50',),('10'),)
      

      使用以下代码获取列表格式的数据

      >>> results=(('58',),('50',),('10'),)
      >>>[x[0] for x in results] --> code
         ['58', '50', '1']
      

      【讨论】:

        【解决方案4】:

        56L 是一个long integer。 “长整数具有无限精度。”它们可以像普通整数一样使用。

        您可以通过执行以下操作来查看 long 值:

        for result in results:
            print result[0]
        

        REPL 会话示例:

        >>> results = ((56L,),)
        >>> for result in results:
        ...     print(result[0])
        ...
        56
        

        .fetchall()the DB-API 中定义为“作为序列序列(例如元组列表)”返回剩余行。 MySQLdb 的默认设置是使用一个元组元组,看起来像这样 (( ,),) 甚至像这样 ( (1,2,3), (4,5,6) ) 其中结果集的各个行是内部元组 - 因此总是具有相同的长度。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-05-13
          • 2010-12-05
          • 1970-01-01
          • 2018-02-09
          • 2010-10-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多