Outils pour utilisateurs

Outils du site


postgresql:python

Ceci est une ancienne révision du document !


PostgreSQL avec Python 3

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

cusor = conn.cursor()
try:
    cursor.execute("""
        select *
        from my_table
        where id > %s
        order by id;
        """, (id,))
    rows = cursor.fetchall()
finally:
    cursor.close()
postgresql/python.1594618373.txt.gz · Dernière modification: 2020/07/13 05:32 (modification externe)