w3resource

Using Psycopg2 with PostgreSQL in Python: Full Guide with Examples


Using PostgreSQL with Psycopg2 in Python

Psycopg2 is a popular PostgreSQL adapter for Python, known for its speed, ease of use, and ability to manage complex queries. This guide will explain how to install Psycopg2, set up connections, and perform basic CRUD operations with PostgreSQL in Python.

Step 1: Install Psycopg2

To use Psycopg2, you’ll need to install it. Use the following pip command:

pip install psycopg2

For additional functionality, consider installing psycopg2-binary, which includes pre-compiled binaries:

pip install psycopg2-binary

Step 2: Setting Up a Connection

Here's how to configure the connection to your PostgreSQL database in Python:

Code:

# Import the psycopg2 library
import psycopg2

# Define the connection parameters
connection = psycopg2.connect(
    dbname="your_database",    # Database name
    user="your_username",      # PostgreSQL username
    password="your_password",  # Password for the user
    host="localhost",          # Database host
    port="5432"                # Database port
)

# Open a cursor to perform database operations
cursor = connection.cursor()

# Print a success message
print("Connected to PostgreSQL")

Step 3: Create a Table

With the connection established, you can create tables within PostgreSQL:

Code:

# Define the SQL query for creating a table
create_table_query = '''
CREATE TABLE IF NOT EXISTS employees (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100),
    position VARCHAR(100),
    hire_date DATE
);
'''

# Execute the create table query
cursor.execute(create_table_query)
connection.commit()  # Commit the transaction
print("Table created successfully")

Step 4: CRUD Operations Using Psycopg2

Insert Data

Here's how to insert data into the employees table:

Code:

# Define an insert function
def insert_employee(name, position, hire_date):
    insert_query = '''
    INSERT INTO employees (name, position, hire_date)
    VALUES (%s, %s, %s) RETURNING id;
    '''
    cursor.execute(insert_query, (name, position, hire_date))
    connection.commit()
    print("Employee inserted with ID:", cursor.fetchone()[0])

# Example usage
insert_employee("Alice Smith", "Developer", "2023-05-21")

Query Data

Retrieve and print all data from the employees table:

Code:

# Define a fetch function
def fetch_employees():
    cursor.execute("SELECT * FROM employees;")
    rows = cursor.fetchall()
    for row in rows:
        print(row)

# Example usage
fetch_employees()

Update Data

Here’s how to update an employee’s position by their ID:

Code:

# Define an update function
def update_employee_position(emp_id, new_position):
    update_query = '''
    UPDATE employees
    SET position = %s
    WHERE id = %s;
    '''
    cursor.execute(update_query, (new_position, emp_id))
    connection.commit()
    print("Employee position updated")

# Example usage
update_employee_position(1, "Senior Developer")

Delete Data

Delete an employee by their ID:

# Define a delete function
def delete_employee(emp_id):
    delete_query = '''
    DELETE FROM employees WHERE id = %s;
    '''
    cursor.execute(delete_query, (emp_id,))
    connection.commit()
    print("Employee deleted")

# Example usage
delete_employee(1)

Explanation of Code:

  • Connection Setup: Defines the database connection using psycopg2.connect.
  • Table Creation: Executes SQL to create the employees table if it does not exist.
  • CRUD Functions: Defines functions for inserting, querying, updating, and deleting rows using parameterized queries to enhance security.

Step 5: Close the Connection

After performing all operations, it’s good practice to close the connection:


# Close the cursor and connection
cursor.close()
connection.close()
print("Connection closed")

Additional Information:

  • Parameterization: The %s placeholders prevent SQL injection by allowing Psycopg2 to safely handle user input.
  • Error Handling: Wrap database operations in try-except blocks for production code to handle exceptions effectively.
  • Transactions: Use connection.commit() to save changes. For complex queries, transactions can ensure data consistency.

All PostgreSQL Questions, Answers, and Code Snippets Collection.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/PostgreSQL/snippets/postgresql-psycopg2-guide.php