À quoi servent commit, connection, cursor et close ?
📁 itérateur, Sujets avancés sur Python, exemple
Exemple de base
import psycopg2# Connect to an existing databaseconn = psycopg2.connect(""dbname=test user=postgres"")# Open a cursor to perform database operationscur = conn.cursor()# Execute a command: this creates a new tablecur.execute(""CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);"")# Pass data to fill a query placeholders and let Psycopg perform# the correct conversion (no more SQL injections!)cur.execute(""INSERT INTO test (num, data) VALUES (%s, %s)"",... (100, ""abc'def""))# Query the database and obtain data as Python objectscur.execute(""SELECT * FROM test;"")cur.fetchone()# Make the changes to the database persistentconn.commit()