[파이썬] Psycopg2에서 Server-side prepared statements

If you are working with PostgreSQL databases in Python, chances are you have come across Psycopg2, the most popular PostgreSQL adapter for Python. Psycopg2 allows us to interact with the PostgreSQL database and execute SQL queries from our Python code.

In this blog post, we will explore how to use server-side prepared statements in Psycopg2. Prepared statements are a useful feature of databases that allow us to pre-compile SQL statements and execute them multiple times with different parameter values. This can improve performance and security by preventing SQL injection attacks.

To begin, let’s first make sure we have Psycopg2 installed. If not, we can install it using pip:

pip install psycopg2

Now, let’s assume we have a table called “users” in our PostgreSQL database with two columns: “id” and “name”. We want to insert multiple rows into this table using prepared statements.

Here’s an example of how we can use server-side prepared statements in Psycopg2:

import psycopg2

# Establish a connection to the PostgreSQL database
conn = psycopg2.connect(
    host="localhost",
    database="mydatabase",
    user="myuser",
    password="mypassword"
)

# Create a cursor object to execute SQL queries
cursor = conn.cursor()

# Prepare the INSERT statement
prepare_query = "PREPARE insert_users AS INSERT INTO users (id, name) VALUES ($1, $2)"

# Execute the prepared statement
cursor.execute(prepare_query)

# Define the data to be inserted
data = [
    (1, "John"),
    (2, "Jane"),
    (3, "Alice")
]

# Execute the prepared statement multiple times with different parameter values
for row in data:
    cursor.execute("EXECUTE insert_users (%s, %s)", row)

# Commit the changes to the database
conn.commit()

# Close the cursor and the database connection
cursor.close()
conn.close()

In the above code, we first establish a connection to the PostgreSQL database using the psycopg2.connect() function. Then, we create a cursor object to execute the SQL queries.

Next, we prepare the INSERT statement using the PREPARE keyword followed by the query itself. This statement sets up a prepared statement named “insert_users” that expects two parameters.

After preparing the statement, we can execute it multiple times with different parameter values using the EXECUTE statement. In this example, we insert three rows into the “users” table.

Finally, we commit the changes to the database and close the cursor and the database connection.

Using server-side prepared statements in Psycopg2 can help us improve performance and security when working with PostgreSQL databases in Python. It allows us to easily reuse SQL queries with different parameter values, reducing the overhead of parsing and compiling the queries each time they are executed.