如何使用psycopg2定义函数

0 投票
1 回答
33 浏览
提问于 2025-04-12 15:37

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

我正在尝试使用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"))

我该如何将查询添加到函数中呢?

1 个回答

1

根据需要做出合适的修改

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)

撰写回答