PostgreSQL est un système de gestion de bases de données relationnelles open source. Nous verrons connecter se connecter à une base de donnée PostgreSQL et effectuer les opérations CRUD.
Download Postgres's setup here https://www.enterprisedb.com/downloads/postgres-postgresql-downloads
$ pip install -q psycopg2-binary
Create a new database called algojungle.
# !pip install -q psycopg2-binary # !pip install -q pandas from getpass import getpass import psycopg2 import pandas as pd
HOST = 'localhost' DATABASE = 'algojungle' USER = 'postgres'
PASSWORD = getpass("Enter Password: ") conn = psycopg2.connect(host=HOST, database=DATABASE, user=USER, password=PASSWORD)
Enter Password: ········
# Create a cursor cur = conn.cursor()
sql1 = "DROP TABLE IF EXISTS customers;"; sql2 = """ CREATE TABLE customers ( DepartmentID INTEGER PRIMARY KEY NOT NULL, Name VARCHAR(100), GroupName VARCHAR(100) ); """ cur.execute(sql1) cur.execute(sql2) conn.commit()
sql3 = """ INSERT INTO customers (DepartmentID, Name, GroupName) VALUES (1, 'Engineering', 'Research and Development'), (2, 'Tool Design', 'Research and Development'), (3, 'Sales', 'Sales and Marketing'), (4, 'Marketing', 'Sales and Marketing'), (5, 'Purchasing', 'Inventory Management'), (6, 'Research and Development', 'Research and Development'), (7, 'Production', 'Manufacturing'), (8, 'Production Control', 'Manufacturing'), (9, 'Human Resources', 'Executive General and Administration'), (10, 'Finance', 'Executive General and Administration'), (11, 'Information Services', 'Executive General and Administration'), (12, 'Document Control', 'Quality Assurance'), (13, 'Quality Assurance', 'Quality Assurance'), (14, 'Facilities and Maintenance', 'Executive General and Administration'), (15, 'Shipping and Receiving', 'Inventory Management'), (16, 'Executive', 'Executive General and Administration'); """ cur.execute(sql3) conn.commit()
sql4 = "SELECT * FROM customers;" cur.execute(sql4) results = pd.DataFrame(cur.fetchall(), columns=[desc[0] for desc in cur.description]) results
sql5 = """ UPDATE customers SET Name = 'Updated Engineering' WHERE DepartmentID = 1; """ cur.execute(sql5) conn.commit() cur.execute(sql4) results = pd.DataFrame(cur.fetchall(), columns=[desc[0] for desc in cur.description]) results
sql6 = """ DELETE FROM customers WHERE DepartmentID = 1; """ cur.execute(sql6) conn.commit() cur.execute(sql4) results = pd.DataFrame(cur.fetchall(), columns=[desc[0] for desc in cur.description]) results
# close the communication with the PostgreSQL cur.close() conn.close() print('Database connection closed.')
Database connection closed.