How to define a function using psycopg2

35 Views Asked by At

This is my first question here, so thanks in advance to anyone replying to this humble student.

I'm trying to define a function using psycopg2. I have split into two stages. First the parameters necessary for connection, which I managed to read through documentation and solve. Now, my issue is dealing with the query to pass it through the function. Ex:

def databasequery(database, user, password, host, port): 
            psycopg2.connect( 
            database=database, 
            user=user, 
            password=password, 
            host=host, 
            port=port, 
        ) 
 
conn = get_connection() 
  
curr = conn.cursor() 
  
print(databasequery("Select * from customers", "your_database","your_user","your_password","your_host","your_port"))

How can I add the query to pass through the function?

1

There are 1 best solutions below

3
mac On

Make suitable changes as needed

import psycopg2

def create_function(sql_query):
    try:
        # Connect to your PostgreSQL database
        conn = psycopg2.connect(
            dbname="your_database",
            user="your_username",
            password="your_password",
            host="your_host",
            port="your_port"
        )
        # Create a cursor object
        cur = conn.cursor()
        
        # Execute the SQL query to create the function
        cur.execute(sql_query)
        
        # Commit the transaction
        conn.commit()

        # Close the cursor and connection
        cur.close()
        conn.close()
        
        print("Function created successfully")

    except psycopg2.Error as e:
        print("Error:", e)


# Example usage: Define the SQL query for the function
sql_query = """
Select * from customers", "your_database","your_user","your_password","your_host","your_port
"""

# Call the function to create the function
create_function(sql_query)