【问题标题】:Fetch data with pymysql (DictCursor)使用 pymysql (DictCursor) 获取数据
【发布时间】:2014-06-02 18:53:01
【问题描述】:

这似乎是一项非常简单的任务,但我很难正确完成。

我的 SQL 查询如下所示:

self.link = self.db.cursor(pymysql.cursors.DictCursor);
self.link.execute("SELECT * FROM crawler_data WHERE id=%d" % id_crawl)

我想通过以下方式访问列:

row = self.link.fetchall()
if row["address"]:
    self.address = self.filterAddress(row["address"])

我收到错误"list indices must be integers, not str"

当我打印 row 时,我得到以下结构返回:

{u'address': 'Address Value', u'domain': 'Domain Value'}

如何访问“地址”字符串?

【问题讨论】:

    标签: python pymysql


    【解决方案1】:

    在上面的例子中,我试图只选择 1 个结果 (WHERE id=:%d),然后检查它是否设置了 address。为此,使用self.link.fetchall() 不是一个好主意,因为这会返回一个包含所有结果的列表,例如可以在循环中使用。

    正确使用的函数是self.link.fetchone(),它只返回字典。如果你使用:

    row = self.link.fetchone()
    

    那么你也可以使用

    print row["key"]
    

    如果你使用

    row = self.link.fetchall()
    

    那么你必须使用

    print row[0]["key"]
    

    【讨论】:

      【解决方案2】:

      fetchall() 的结果将是一个字典列表。在您的示例中,通过

      访问字符串
      results = self.link.fetchall()
      row = results[0]
      self.address = self.filterAddress(row["address"])
      

      【讨论】:

        猜你喜欢
        • 2014-06-05
        • 2019-08-01
        • 2019-09-01
        • 2021-12-06
        • 1970-01-01
        • 2021-06-23
        • 2018-08-10
        • 2018-09-21
        • 2020-12-08
        相关资源
        最近更新 更多