如何使用psycopg2定义函数

问题描述 投票:0回答:1

这是我的第一个问题,所以提前感谢任何回复这位谦虚学生的人。

我正在尝试使用 psycopg2 定义一个函数。我分为两个阶段。首先是连接所需的参数,我设法阅读文档并解决。现在,我的问题是处理查询以将其传递给函数。例如:

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"))

如何添加查询来传递函数?

python sql psycopg2
1个回答
0
投票

根据需要进行适当的更改

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)

© www.soinside.com 2019 - 2024. All rights reserved.