【问题标题】:Single column fetch returning in list in python postgresql在 python postgresql 的列表中返回单列获取
【发布时间】:2021-08-19 05:29:45
【问题描述】:

数据库:

id trade token
1 abc 5523
2 fdfd 5145
3 sdfd 2899

代码:

def db_fetchquery(sql):
    conn    = psycopg2.connect(database="trade", user='postgres', password='jps', host='127.0.0.1', port= '5432')
    cursor = conn.cursor()
    conn.autocommit = True
    cursor.execute(sql)
    row = cursor.rowcount
    if row >= 1:
        data = cursor.fetchall()
        conn.close()
        return data
    conn.close()
    return False

print(db_fetchquery("SELECT token FROM script"))

结果:

[(5523,),(5145,),(2899,)]

但我需要如下结果:

[5523,5145,2899]

我也试过print(db_fetchquery("SELECT zerodha FROM script")[0]),但结果是:- [(5523,)]

另外,当我只获取一列时,为什么列表内有“,”/列表?

【问题讨论】:

  • , 是 Python 核心开发人员发现的一种消除元组与一个元素和一个表达式的歧义的方法。因此,例如,在您的情况下,(5523,) 是一个具有单个元素的元组,5523

标签: python sql python-3.x postgresql list


【解决方案1】:

不确定您是否能够在不进行进一步处理的情况下做到这一点,但我会这样做:

data = [x[0] for x in data]

将元组列表转换为一维列表

【讨论】:

    猜你喜欢
    • 2010-11-21
    • 1970-01-01
    • 1970-01-01
    • 2020-01-25
    • 2022-01-27
    • 2014-10-15
    • 1970-01-01
    • 2021-09-27
    相关资源
    最近更新 更多