1 | initial version |
A "where in" query can be executed using the MariaDB Python Connector by using the following steps:
Import the mariadb connector in your Python program:
import mariadb
Connect to your MariaDB/MySQL server:
conn = mariadb.connect(
user="username",
password="password",
host="localhost",
database="databasename"
)
Create a cursor object:
cur = conn.cursor()
Write the "where in" query by passing a tuple of values to the execute()
method:
values = ("value1", "value2", "value3")
cur.execute("SELECT * FROM table WHERE column_name IN (%s,%s,%s)", values)
Note that the %s
placeholders in the query string are replaced with the values from the tuple.
You can then fetch the results using the fetchall()
method:
results = cur.fetchall()
for row in results:
print(row)
Finally, close the cursor and connection objects:
cur.close()
conn.close()
Here is the complete code:
import mariadb
conn = mariadb.connect(
user="username",
password="password",
host="localhost",
database="databasename"
)
cur = conn.cursor()
values = ("value1", "value2", "value3")
cur.execute("SELECT * FROM table WHERE column_name IN (%s,%s,%s)", values)
results = cur.fetchall()
for row in results:
print(row)
cur.close()
conn.close()