1 | initial version |
The procedure for executing a PostgreSQL query with multiple parameters of diverse values can vary depending on how you are interacting with the database. Here are a few possible ways to do it:
psql mydatabase -c "SELECT * FROM mytable WHERE column1 = $1 AND column2 = $2" --param1=value1 --param2=value2
This will substitute the values of value1
and value2
for the placeholders $1
and $2
in the query. You can provide as many parameters as you need, separated by spaces after the query text.
import psycopg2
conn = psycopg2.connect(database="mydatabase", user="myuser", password="mypassword", host="localhost", port="5432")
cursor = conn.cursor()
query = "SELECT * FROM mytable WHERE column1 = %s AND column2 = %s"
params = (value1, value2)
cursor.execute(query, params)
rows = cursor.fetchall()
conn.close()
In this example, the %s
placeholders in the query text are replaced by the values in the params
tuple. You can use as many placeholders and parameters as you need.
import java.sql.*;
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost/mydatabase", "myuser", "mypassword");
String query = "SELECT * FROM mytable WHERE column1 = ? AND column2 = ?";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, value1);
pstmt.setString(2, value2);
ResultSet rs = pstmt.executeQuery();
conn.close();
In this example, the ?
placeholders in the query text are replaced by calls to the setString
method on the prepared statement. You can use as many placeholders and parameters as you need, and you can use different types of setters depending on the data types of your parameters.