PostgreSQL Query Execution with psycopg2

  • Share this:

Code introduction


This function connects to a PostgreSQL database, executes an SQL query, and returns the query results. It uses the psycopg2 library to connect to the database, execute the query, and fetch the results.


Technology Stack : psycopg2

Code Type : Database Query Execution

Code Difficulty : Intermediate


                
                    
import psycopg2
import random

def connect_and_query(host, database, user, password, query):
    """
    Connect to a PostgreSQL database and execute a query.
    """
    # Connect to the PostgreSQL database
    conn = psycopg2.connect(
        host=host,
        database=database,
        user=user,
        password=password
    )
    
    # Create a cursor object using the cursor() method
    cursor = conn.cursor()
    
    # Execute the query
    cursor.execute(query)
    
    # Fetch all the records
    records = cursor.fetchall()
    
    # Close the cursor and connection
    cursor.close()
    conn.close()
    
    return records

# Example usage
if __name__ == "__main__":
    # Define connection parameters
    host = 'localhost'
    database = 'mydatabase'
    user = 'myuser'
    password = 'mypassword'
    query = 'SELECT * FROM mytable;'
    
    # Call the function
    result = connect_and_query(host, database, user, password, query)
    print(result)                
              
Tags: