tech:notes_postgres_python
Différences
Ci-dessous, les différences entre deux révisions de la page.
| Les deux révisions précédentesRévision précédente | |||
| tech:notes_postgres_python [2025/11/20 16:38] – Jean-Baptiste | tech:notes_postgres_python [2026/06/07 19:12] (Version actuelle) – modification externe 127.0.0.1 | ||
|---|---|---|---|
| Ligne 1: | Ligne 1: | ||
| + | < | ||
| + | {{tag> | ||
| + | |||
| + | # Notes Postgres Python | ||
| + | |||
| + | Voir : | ||
| + | * http:// | ||
| + | * http:// | ||
| + | |||
| + | Voir aussi : | ||
| + | * [[connexion_a_une_base_proprietaire_-_python_-_jdbc_-_odbc|Connexion à une base propriétaire - Python - JDBC - ODBC]] | ||
| + | * pg8000 | ||
| + | * python-sqlalchemy | ||
| + | |||
| + | ## Exemple | ||
| + | |||
| + | Vacuum | ||
| + | ~~~python | ||
| + | dbname = ' | ||
| + | user = ' | ||
| + | host = ' | ||
| + | password = ' | ||
| + | |||
| + | import psycopg2 | ||
| + | c = " | ||
| + | conn = psycopg2.connect(c % (dbname, user, host, password)) | ||
| + | conn.set_session(autocommit=True) | ||
| + | cur=conn.cursor() | ||
| + | |||
| + | cur.execute(" | ||
| + | cur.close() | ||
| + | conn.close() | ||
| + | ~~~ | ||
| + | |||
| + | Query select - Fetch | ||
| + | |||
| + | ~~~python | ||
| + | cur=conn.cursor() | ||
| + | cur.execute(" | ||
| + | if cur.rowcount > 0: | ||
| + | row = cur.fetchone() | ||
| + | else: | ||
| + | row = None | ||
| + | while row is not None: | ||
| + | print(row) | ||
| + | row = cur.fetchone() | ||
| + | |||
| + | cur.close() | ||
| + | conn.commit() | ||
| + | conn.close() | ||
| + | ~~~ | ||
| + | |||
| + | ## with statement | ||
| + | |||
| + | Source : https:// | ||
| + | |||
| + | ~~~python | ||
| + | conn = psycopg2.connect(DSN) | ||
| + | |||
| + | with conn: | ||
| + | with conn.cursor() as curs: | ||
| + | curs.execute(SQL1) | ||
| + | |||
| + | with conn: | ||
| + | with conn.cursor() as curs: | ||
| + | curs.execute(SQL2) | ||
| + | |||
| + | conn.close() | ||
| + | ~~~ | ||
| + | |||
| + | ### Warning | ||
| + | |||
| + | Unlike file objects or other resources, exiting the connection’s with block doesn’t close the connection, but only the transaction associated to it. If you want to make sure the connection is closed after a certain point, you should still use a try-catch block : | ||
| + | ~~~python | ||
| + | conn = psycopg2.connect(DSN) | ||
| + | try: | ||
| + | # connection usage | ||
| + | finally: | ||
| + | conn.close() | ||
| + | ~~~ | ||
| + | |||
| + | |||
| + | |||
