In diesem Artikel werden wir besprechen, wie man eine Python-Liste mit dem Modul pyscopg2 in die PostgreSQL-Datenbank einfügt.

Psycopg2 ist der beliebteste PostgreSQL-Adapter für die Programmiersprache Python. Psycopg2 ist ein DB API 2.0-kompatibler PostgreSQL-Treiber, der aktiv entwickelt wird. Es ist für Multithread-Anwendungen ausgelegt und verwaltet seinen eigenen Verbindungspool. Dieses Modul kann mit dem angegebenen Befehl installiert werden:

pip install psycopg2

Um alle Datensätze einzufügen, wird die Liste durchlaufen und die Werte einzeln eingefügt.

Syntax :

list = [(),(),.....,()]
for d in list:
    cursor.execute("INSERT into table_name(
    column1,column2, colum3.....) VALUES (%s, %s, %s,.....)", d)

Importieren Sie zunächst alle benötigten Bibliotheken in den Arbeitsbereich und stellen Sie die Datenbankverbindung her. Setzen Sie auto-commit auf false und erstellen Sie ein Cursor-Objekt. Erstellen Sie nun eine Liste mit Daten, die in die Tabelle eingefügt werden sollen. Durchlaufen Sie die Liste und fügen Sie Werte ein. Bestätigen und Verbindung schließen.

Beispiel: Einfügen von Listenwerten in die Datenbank

Python3

# importing psycopg2 module
import psycopg2
  
# establishing the connection
conn = psycopg2.connect(
    database="postgres",
    user='postgres',
    password='password',
    host='localhost',
    port='5432'
)
  
# creating a cursor object
cursor = conn.cursor()
  
# creating table
sql = '''CREATE TABLE employee(
 id  SERIAL NOT NULL,
 name varchar(20) not null,
 state varchar(20) not null
)'''
  
  
# list that contain records to be inserted into table
data = [('Babita', 'Bihar'), ('Anushka', 'Hyderabad'), 
        ('Anamika', 'Banglore'), ('Sanaya', 'Pune'),
        ('Radha', 'Chandigarh')]
  
# inserting record into employee table
for d in data:
    cursor.execute("INSERT into employee(name, state) VALUES (%s, %s)", d)
  
  
print("List has been inserted to employee table successfully...")
  
# Commit your changes in the database
conn.commit()
  
# Closing the connection
conn.close()

Ausgabe:

Die Liste wurde erfolgreich in die Mitarbeitertabelle eingefügt

Beispiel: Prüfen, ob Daten in der Mitarbeitertabelle angezeigt werden oder nicht. 

Python3

# importing psycopg2 module
import psycopg2
  
# establishing the connection
conn = psycopg2.connect(
    database="postgres",
    user='postgres',
    password='password',
    host='localhost',
    port='5432'
)
  
# creating cursor object
cursor = conn.cursor()
  
# query to sort table by name
sql2 = 'select * from employee;'
# executing query
cursor.execute(sql2)
  
# fetching the result
print(cursor.fetchall())
  
# Commit your changes in the database
conn.commit()
  
# Closing the connection
conn.close()

Ausgabe

[(1, 'Babita', 'Bihar'), (2, 'Anushka', 'Hyderabad'), (3, 'Anamika', 'Banglore'), (4, 'Sanaya', 'Pune'), ( 5, 'Radha', 'Chandigarh')]