PostgreSQL and PdAdmin Installation
Installation
sudo apt update
sudo apt install postgresql postgresql-contrib
Command Lines
sudo -u postgres psql # username and postgresql --> postgres=#
\q # quit
\dt # list table
\d # list table and sequence
### SQL Commands
CREATE TABLE color (
id INT,
name VARCHAR(100) NOT NULL,
PRIMARY KEY (id));
### Insert
INSERT INTO color (id, name) VALUES (1,'red');
### Select
SELECT * FROM color;
Python Connection
pip install psycopg2
### Script
import psycopg2
from psycopg2 import Error
try:
connection = psycopg2.connect(user="postgres",
password="postgres",
host="127.0.0.1",
port="5432",
database="postgres")
# database name can be from 'SELECT current_database();'
cursor = connection.cursor()
print("PostgreSQL server information")
print(connection.get_dsn_parameters(), "\n")
cursor.execute("SELECT version();")
record = cursor.fetchone()
print("You are connected to - ", record, "\n")
except (Exception, Error) as error:
print("Error while connecting to PostgreSQL", error)
### Insert
cursor.execute("INSERT INTO color (id, name) VALUES (2, 'blue')")
connection.commit()
### Select
cursor.execute('SELECT * FROM color;')
record = cursor.fetchall()
print('Result ',record)
### Close
if (connection):
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
References
- An Introduction to Postgres with Python
- PostgreSQL - PgAdmin 4 - Import csv file using PgAdmin
- PostgreSQL Python: Create Tables
- Python: Read a CSV file line by line with or without header
- Import CSV File Into PostgreSQL Table
- How To Install and Use PostgreSQL on Ubuntu 18.04
- Python PostgreSQL Tutorial Using Psycopg2