====== PostgreSQL avec Python 3 ======
Sources:
* [[https://pynative.com/python-postgresql-tutorial/]]
* [[https://pynative.com/python-postgresql-select-data-from-table/]]
===== Installation de Psycopg2 =====
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
===== Connexion / Déconnexion =====
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()
===== Requête =====
Renvoie un objet **list** dont chaque élément est un **tuple** :
cursor = conn.cursor()
try:
cursor.execute("""
select id, name, price
from products
where id >= %s
order by id;
""", (id,))
rows = cursor.fetchall()
print(type(rows))
for row in rows:
print(type(row))
print(row)
finally:
cursor.close()
Exemple de résultat :
(5, 'Bananes', Decimal('3.76'))
(6, 'Oranges', Decimal('6.20'))