Ceci est une ancienne révision du document !
Sources:
Si pip3 (l'installateur de modules de Python 3) n'est pas installé :
sudo apt install python3-pip
Ensuite installer Psycopg2 :
sudo pip3 install psycopg2
import getpass, psycopg2 username = "postgres" password = None conn = None def connect(): global conn try: conn = psycopg2.connect( user = username, password = password, host = "localhost", port = "5432", database = "my_database") except(Exception, psycopg2.Error) as error: conn = None print("Error while connecting:", error) def disconnect(): global conn if conn: conn.close print("Connection is closed") password = getpass.getpass("Password for user %s :" % username) try: connect() if conn: print("Connection OK") finally: disconnect()
cusor = conn.cursor() try: cursor.execute(""" select * from my_table where id > %s order by id; """, (id,)) rows = cursor.fetchall() finally: cursor.close()