Select only returns result in terminal

Asked

Viewed 43 times

0

I’m having trouble understanding why the code below only returns result when executed in the terminal.

I intend to return hash of the last id entered in the database

connection = psycopg2.connect("dbname=vone")
cursor = connection.cursor()
SQL = """
  SELECT hash
  FROM pos_order
  WHERE id = ( SELECT max(id) FROM pos_order );"""
cursor.execute(SQL)
hash = cursor.fetchone()[0]

When executing the code within a function, the method cursor.fetchone() returns None.

  • Ask the question SQL CREATE TABLE pos_order and a data sample (text format) for testing.

1 answer

0

I believe that the problem is in getting the connection, because as you said yourself, the query is working when consulting through the terminal.

To solve:
Change the form of connection by informing the required parameters.

import psycopg2
connection = psycopg2.connect("dbname='vone' user='postgres' host='localhost' password='123456'")
print(connection)
cursor = connection.cursor()
SQL = """
  SELECT hash
  FROM pos_order
  WHERE id = ( SELECT max(id) FROM pos_order )"""
cursor.execute(SQL)
hash = cursor.fetchone()[0]
print(hash)

For viewing purposes, added two prints:

print(connection)
...
print(hash)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.