PostgreSQL Database access using psycopg2
suggest changepsycopg2 is the most popular PostgreSQL database adapter that is both lightweight and efficient. It is the current implementation of the PostgreSQL adapter.
Its main features are the complete implementation of the Python DB API 2.0 specification and the thread safety (several threads can share the same connection)
Establishing a connection to the database and creating a table
import psycopg2
# Establish a connection to the database.
# Replace parameter values with database credentials.
conn = psycopg2.connect(database="testpython",
user="postgres",
host="localhost",
password="abc123",
port="5432")
# Create a cursor. The cursor allows you to execute database queries.
cur = conn.cursor()
# Create a table. Initialise the table name, the column names and data type.
cur.execute("""CREATE TABLE FRUITS (
id INT ,
fruit_name TEXT,
color TEXT,
price REAL
)""")
conn.commit()
conn.close()
Inserting data into the table:
# After creating the table as shown above, insert values into it.
# The previous snippet has already called conn.close(), so this cursor is closed.
cur.execute("""INSERT INTO FRUITS (id, fruit_name, color, price)
VALUES (1, 'Apples', 'green', 1.00)""")
cur.execute("""INSERT INTO FRUITS (id, fruit_name, color, price)
VALUES (1, 'Bananas', 'yellow', 0.80)""")
Retrieving table data:
The inserts above both use id 1, and this page never runs a SELECT. The listing below does not follow from that code. It shows ID = 2 for Bananas. psycopg2 is not installed here, so the samples were not run.
ID = 1
NAME = Apples
COLOR = green
PRICE = 1.0
ID = 2
NAME = Bananas
COLOR = yellow
PRICE = 0.8
And so, there you go, you now know half of all you need to know about psycopg2! :)
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents