【问题标题】:Returning Dict from SQlite3 Database query return sqlite3.Row error从 SQlite3 数据库查询返回字典返回 sqlite3.Row 错误
【发布时间】:2021-06-25 23:00:57
【问题描述】:

我正在运行一个函数,该函数当前通过从 SQLite 数据库中提取数据来打印字典列表。但是,当使用 return 而不是 print 时,我得到一个错误,因为 sqlite3.Row object at 0x04AD4980 并且没有数据显示(在调试模式下)。

根据我的阅读,为了从 Sql 查询中返回 dict 数据格式,我应该使用 row_factory 我做过并且工作过的仅打印时很好。

请问有什么办法吗?

数据库详情: 数据库名称: 'testDB'

Test_Table:姓名、年龄、出生日期

import sqlite3

    def queryData () :

        conn = sqlite3.connect ( 'TestDB.db' )
        # row_factory to create dictionary cursor
        conn.row_factory = sqlite3.Row
        cursor = conn.cursor ( )
    
        cursor.execute ( "select * from test_table" )
        rows = cursor.fetchall ( )
    
        for row in rows :
            
            return ({ row [ 'name' ] } , { row [ 'age' ] } , { row [ 'dob' ] })
            ## with print, it works
            ## print ({ row [ 'name' ] } , { row [ 'age' ] } , { row [ 'dob' ] })
    
    
    def main () :
        queryData ( )

【问题讨论】:

  • 哪一行给出了什么错误?贴出的代码不会产生错误(当执行main 并且至少选择了一行时)。
  • 返回行给出调试模式下的错误。如果在没有调试模式的情况下执行,你不会看到任何错误

标签: python-3.x sqlite


【解决方案1】:

这不是错误。它告诉你row 是一个sqlite3.Row object,它位于 那个内存位置。这个 sn-p 不会对 row “做”任何事情,除非它是 printed。正如所写,它工作正常。

使用行工厂不会返回 dict 对象。它返回一个 sqlite3.Row 对象,该对象“支持按列名进行映射访问”,就像字典一样。也许更仔细地研究示例in the doc,看看如何使用行工厂来构建您想要的程序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-19
    • 2017-05-10
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    相关资源
    最近更新 更多