Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

A "where in" query can be executed using the MariaDB Python Connector by using the following steps:

  1. Import the mariadb connector in your Python program:

    import mariadb
    
  2. Connect to your MariaDB/MySQL server:

    conn = mariadb.connect(
       user="username",
       password="password",
       host="localhost",
       database="databasename"
    )
    
  3. Create a cursor object:

    cur = conn.cursor()
    
  4. 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.

  5. You can then fetch the results using the fetchall() method:

    results = cur.fetchall()
    for row in results:
       print(row)
    
  6. 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()