python的新手,尝试使用psycopg2来阅读Postgres
我正在从名为deployment的数据库表中读取并尝试从具有三个字段id,Key和Value的表中处理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"]]
我希望这只是“newdrive”,以便我可以在下一行进行字符串比较,以检查它是否是“newdrive”
我在json.dumps输出上尝试了json.loads,但没有用
>>> a=json.loads(json.dumps(records))
>>> print(a)
[['newdrive']]
I also tried to print just the records without json.dump
>>> print(records)
[('newdrive',)]
fetchall()
的结果是一系列元组。您可以遍历序列并打印每个元组的第一个(索引0)元素:
cur.execute("SELECT \"Value\" FROM deployment WHERE (\"Key\" = 'DUMPLOCATION')")
records = cur.fetchall()
for record in records:
print(record[0])
或者更简单,如果您确定查询返回的行数不超过一行,请使用fetchone()
,它给出一个表示返回行的元组,例如:
cur.execute("SELECT \"Value\" FROM deployment WHERE (\"Key\" = 'DUMPLOCATION')")
row = cur.fetchone()
if row: # check whether the query returned a row
print(row[0])