Ci-dessous, les différences entre deux révisions de la page.
Les deux révisions précédentes Révision précédente Prochaine révision | Révision précédente | ||
postgresql:python [2020/07/12 07:21] marclebrun |
postgresql:python [2020/07/13 05:48] (Version actuelle) marclebrun [Requête] |
||
---|---|---|---|
Ligne 1: | Ligne 1: | ||
====== PostgreSQL avec Python 3 ====== | ====== PostgreSQL avec Python 3 ====== | ||
- | Source: [[https://pynative.com/python-postgresql-tutorial/]] | + | Sources: |
+ | * [[https://pynative.com/python-postgresql-tutorial/]] | ||
+ | * [[https://pynative.com/python-postgresql-select-data-from-table/]] | ||
===== Installation de Psycopg2 ===== | ===== Installation de Psycopg2 ===== | ||
Ligne 17: | Ligne 19: | ||
</code> | </code> | ||
+ | ===== Connexion / Déconnexion ===== | ||
+ | |||
+ | <code python> | ||
+ | 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() | ||
+ | </code> | ||
+ | |||
+ | ===== Requête ===== | ||
+ | |||
+ | Renvoie un objet **list** dont chaque élément est un **tuple** : | ||
+ | |||
+ | <code python> | ||
+ | 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() | ||
+ | </code> | ||
+ | |||
+ | Exemple de résultat : | ||
+ | |||
+ | <code> | ||
+ | <class 'list'> | ||
+ | <class 'tuple'> | ||
+ | (5, 'Bananes', Decimal('3.76')) | ||
+ | <class 'tuple'> | ||
+ | (6, 'Oranges', Decimal('6.20')) | ||
+ | </code> | ||