Python Language
PostgreSQL
Suche…
Fertig machen
PostgreSQL ist eine aktiv entwickelte und ausgereifte Open-Source-Datenbank. Mit dem Modul psycopg2 können wir Abfragen in der Datenbank ausführen.
Installation mit Pip
pip install psycopg2
Grundlegende Verwendung
my_table wir an, wir haben eine Tabelle my_table in der Datenbank my_database die wie folgt definiert ist.
| Ich würde | Vorname | Nachname |
|---|---|---|
| 1 | John | Damhirschkuh |
Wir können das Modul psycopg2 , um Abfragen in der Datenbank auf folgende Weise auszuführen.
import psycopg2
# Establish a connection to the existing database 'my_database' using
# the user 'my_user' with password 'my_password'
con = psycopg2.connect("host=localhost dbname=my_database user=my_user password=my_password")
# Create a cursor
cur = con.cursor()
# Insert a record into 'my_table'
cur.execute("INSERT INTO my_table(id, first_name, last_name) VALUES (2, 'Jane', 'Doe');")
# Commit the current transaction
con.commit()
# Retrieve all records from 'my_table'
cur.execute("SELECT * FROM my_table;")
results = cur.fetchall()
# Close the database connection
con.close()
# Print the results
print(results)
# OUTPUT: [(1, 'John', 'Doe'), (2, 'Jane', 'Doe')]
Modified text is an extract of the original Stack Overflow Documentation
Lizenziert unter CC BY-SA 3.0
Nicht angeschlossen an Stack Overflow