use*_*834 2 python postgresql psycopg2
我是新手python,正在尝试使用psycopg2阅读Postgres。
我正在从名为部署的数据库表中读取数据,并尝试处理具有三个字段 id、Key 和 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"]]
Run Code Online (Sandbox Code Playgroud)
我希望这只是“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',)]
Run Code Online (Sandbox Code Playgroud)
的结果fetchall()是一个元组序列。您可以循环序列并打印每个元组的第一个(索引 0)元素:
cur.execute("SELECT \"Value\" FROM deployment WHERE (\"Key\" = 'DUMPLOCATION')")
records = cur.fetchall()
for record in records:
print(record[0])
Run Code Online (Sandbox Code Playgroud)
或者更简单,如果您确定查询返回不超过一行,请使用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])
Run Code Online (Sandbox Code Playgroud)