How to use psycopg2 to retrieve a certain key's value from a postgres table which has key-value pairs

…衆ロ難τιáo~ 提交于 2021-02-08 10:01:59

问题


New to python, trying to use psycopg2 to read Postgres

I am reading from a database table called deployment and trying to handle a Value from a table with three fields id, Key and Value

import psycopg2
conn = psycopg2.connect(host="localhost",database=database, user=user, password=password)
cur = conn.cursor()
cur.execute("SELECT \"Value\" FROM deployment WHERE (\"Key\" = 'DUMPLOCATION')")
records = cur.fetchall()
print(json.dumps(records))
[["newdrive"]]

I want this to be just "newdrive" so that I can do a string comparison in the next line to check if its "newdrive" or not

I tried json.loads on the json.dumps output, didn't work

>>> a=json.loads(json.dumps(records))
>>> print(a)
[['newdrive']]

I also tried to print just the records without json.dump
>>> print(records)
[('newdrive',)]

回答1:


The result of fetchall() is a sequence of tuples. You can loop over the sequence and print the first (index 0) element of each tuple:

cur.execute("SELECT \"Value\" FROM deployment WHERE (\"Key\" = 'DUMPLOCATION')")
records = cur.fetchall()
for record in records:
    print(record[0])

Or simpler, if you are sure the query returns no more than one row, use fetchone() which gives a single tuple representing returned row, e.g.:

cur.execute("SELECT \"Value\" FROM deployment WHERE (\"Key\" = 'DUMPLOCATION')")
row = cur.fetchone()
if row: # check whether the query returned a row
    print(row[0])


来源:https://stackoverflow.com/questions/55367647/how-to-use-psycopg2-to-retrieve-a-certain-keys-value-from-a-postgres-table-whic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!