在Python中使用PostgreSQL执行返回None

在Python中使用PostgreSQL执行返回None,python,postgresql,function,Python,Postgresql,Function,这是我的密码 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 = psyco

这是我的密码

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
我将此连接用作
功能(数据,连接)
。 现在,我注意到test命令有奇怪的输出:

_measurement_id = cursor.execute(
    'SELECT measurement_id FROM measurements ORDER BY time desc limit 1;'
);
它通过Python返回
None
,但在
psql
中,我得到一个整数。 我认为错误在于没有使用try-catch,而是创建了连接

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

尝试这样做

try:
    cursor.execute(
    'SELECT measurement_id FROM measurements ORDER BY time desc limit 1;')
    _measurement_id = cursor.fetchone()
except psycopg2.Error as e:
    pass
finally:
    cursor.close()

cursor.execute
不返回任何内容。执行查询后,需要对游标中的行使用
cursor.fetchone
cursor.fetchall
,以检索结果

cursor.execute("...")
_measurement_id = cursor.fetchone()
它与异常处理无关