2

Here is my code

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)

which it is outputting this, which seems to be ok.

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

I use this connection as function(data, conn). Now, I noticed strange outputs with the test command:

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

which returns None through Python but inside psql, I get an integer. I think the mistake is in not using try-catch-except in creating the connection.

And if that is the problem, how can I pass a PostgreSQL connection to functions in Python?

2 Answers 2

4

cursor.execute doesn't return anything. You need to use cursor.fetchone, cursor.fetchall, or for row in cursor: after executing the query to retrieve the results.

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

It has nothing to do with exception handling.

Sign up to request clarification or add additional context in comments.

Comments

0

try do this

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()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.