Single column fetch returning in list in python postgresql

Viewed 338

Database:

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

Code:

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"))

Result:

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

But I need results as:

[5523,5145,2899]

I also tried print(db_fetchquery("SELECT zerodha FROM script")[0]) but this gave result as:- [(5523,)]

Also, why is there ',' / list inside list when I am fetching only one column?

1 Answers

Not sure if you are able to do that without further processing but I would do it like this:

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

which convert the list of tuples to a 1D list

Related