MySQL is a popular open-source relational database management system (RDBMS) that uses SQL (Structured Query Language) to manage its data. In this tutorial, we will learn how to pass a list as a parameter in a MySQL query.
This is helpful when you want to filter or update multiple rows in a table at once. We will be using the Python programming language and the PyMySQL library to execute our MySQL queries.
Step 1: Create a table and insert values
Create a MySql table and insert records for employees.
1 2 3 4 5 6 7 8 9 10 11 12 |
CREATE TABLE employees ( id INT(6) UNSIGNED PRIMARY KEY, name VARCHAR(30) NOT NULL ); INSERT INTO employees (id, name) VALUES (1, 'John'); INSERT INTO employees (id, name) VALUES (2, 'Jane'); INSERT INTO employees (id, name) VALUES (3, 'Bob'); INSERT INTO employees (id, name) VALUES (4, 'Alice'); INSERT INTO employees (id, name) VALUES (5, 'Mike'); INSERT INTO employees (id, name) VALUES (6, 'Sally'); INSERT INTO employees (id, name) VALUES (7, 'Tom'); |
Step 2: Connect to the MySQL Database
Before we can execute any queries, we need to establish a connection to our MySQL database. You can do this with the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import pymysql # Define the connection parameters db = { 'host': 'localhost', 'user': 'your_username', 'password': 'your_password', 'database': 'your_database' } # Establish a connection to the MySQL database connection = pymysql.connect(**db) # Create a cursor object to execute queries cursor = connection.cursor() |
Step 3: Define the List and Create the IN Clause
Let’s create a list of values that we want to use in our MySQL query. After that, we will create a string representation of the IN clause to include these values in our query:
1 2 3 4 5 |
# Define the list of values id_list = [1, 3, 5, 7] # Create the IN clause by joining the values with a comma and wrapping them in parentheses in_clause = '(' + ', '.join(map(str, id_list)) + ')' |
Step 4: Execute the MySQL Query
Now that we have our IN clause, we can incorporate it into a query. In this example, we will select all rows from the “employees” table where the “id” field matches any value in the list:
1 2 3 4 5 6 7 8 |
# Create the MySQL query, inserting the IN clause where needed query = f"SELECT * FROM employees WHERE id IN {in_clause}" # Execute the query cursor.execute(query) # Fetch all the rows as a list of tuples rows = cursor.fetchall() |
Step 5: Process the Query Result
Finally, let’s process the output and print the result:
1 2 3 4 |
# Print the query result print("Fetching all matching rows:") for row in rows: print(row) |
Step 6: Close the Connection
After executing the query and processing the results, don’t forget to close the connection to the MySQL database:
1 2 3 |
# Close the connection cursor.close() connection.close() |
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
import pymysql # Define the connection parameters db = { 'host': 'localhost', 'user': 'your_username', 'password': 'your_password', 'database': 'your_database' } # Establish a connection to the MySQL database connection = pymysql.connect(**db) # Create a cursor object to execute queries cursor = connection.cursor() # Define the list of values id_list = [1, 3, 5, 7] # Create the IN clause by joining the values with a comma and wrapping them in parentheses in_clause = '(' + ', '.join(map(str, id_list)) + ')' # Create the MySQL query, inserting the IN clause where needed query = f"SELECT * FROM employees WHERE id IN {in_clause}" # Execute the query cursor.execute(query) # Fetch all the rows as a list of tuples rows = cursor.fetchall() # Print the query result print("Fetching all matching rows:") for row in rows: print(row) # Close the connection cursor.close() connection.close() |
Output
1 2 3 4 5 |
Fetching all matching rows: (1, 'John') (3, 'Bob') (5, 'Mike') (7, 'Tom') |
Conclusion
In this tutorial, we have learned how to pass a list as a parameter in a MySQL query using Python and the PyMySQL library. This technique can be applied to various types of queries, making it easier to work with multiple values in a single query. Ensure you have closed the connection after processing the results to avoid any potential issues.