gpt4 book ai didi

python - 在 Python 中使用 PostgreSQL 执行返回无

转载 作者:行者123 更新时间:2023-11-29 12:44:34 24 4
gpt4 key购买 nike

这是我的代码

conn_string = "dbname=detector user=postgres password=1234 host=localhost port=5432"
print "Connecting to database\n ->%s" % (conn_string)
# get a connection, if a connect cannot be made an exception will be raised here
conn = psycopg2.connect(conn_string)

它正在输出这个,这似乎没问题。

Connecting to database
->dbname=detector user=postgres password=1234 host=localhost port=5432

我将此连接用作 function(data, conn)。现在,我注意到测试命令有奇怪的输出:

_measurement_id = cursor.execute(
'SELECT measurement_id FROM measurements ORDER BY time desc limit 1;'
);

它通过 Python 返回 None 但在 psql 中,我得到一个整数。我认为错误在于在创建连接时没有使用 try-catch-except。

如果这是问题所在,我如何将 PostgreSQL 连接传递给 Python 中的函数?

最佳答案

cursor.execute 不返回任何内容。您需要在执行查询后使用 cursor.fetchonecursor.fetchallfor row in cursor: 来检索结果。

cursor.execute("...")
_measurement_id = cursor.fetchone()

与异常处理无关。

关于python - 在 Python 中使用 PostgreSQL 执行返回无,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31709748/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com