pythonsqlitesqlite3-python

Correct syntax for python-sqlite3 script? How to select all rows that has a column with a specific value?


I wrote the following python-sqlite3 code. It has two issues:

  1. I want to understand how to write a SQLite3 statement to extract all rows with "cola". What is the correct syntax for the .get_fav_drink_folks(drink) method?

    Error:

    line 25, in get_fav_drink_folks self.cur.execute(sql, drink)
    sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 4 supplied.
    

Script:

import sqlite3

class DB:
    def __init__(self):
        self.con = sqlite3.connect("database.db")
        self.cur = self.con.cursor()
        self.create_table()

    def create_table(self):
        table = """CREATE TABLE IF NOT EXISTS
            database (name TEXT PRIMARY KEY,
                      fav_food TEXT,
                      fav_drink TEXT
                      )"""
        self.cur.execute(table)
        self.con.commit()

    def insert_data_row(self, items):
        sql = """INSERT OR IGNORE INTO database VALUES(?,?,?)"""
        self.cur.execute(sql, items)
        self.con.commit()

    def get_fav_drink_folks(self, drink):
        sql = """SELECT * FROM database WHERE fav_drink in (?)"""
        self.cur.execute(sql, drink)
        return self.cur.fetchmany()


if __name__ in "__main__":
    db = DB()
    data = [
        ("Mike", "Steak", "Cola",),
        ("Dora", "McDonalds", "Sprite",),
        ("Sally", "Salad", "Pepsi",),
        ("Eve", "Pizza", "Cola",),
        ]
    for row_items in data:
        print(f"{row_items=}")
        db.insert_data_row(row_items)
    print(f"\ncoke_drinkers are {db.get_fav_drink_folks('Cola')}")

Solution

    1. You're not instantiating the class. db = DB should be db = DB()

    2. you pass get_fav_drink_folks a string and then use it on self.cur.execute(sql, items)

    You need a tuple like in the other function.

    Either you self.cur.execute(sql, (drink,)) or you cola_drinkers = db.get_fav_drink_folks(('Cola',))

    Edit:

    As for the tuple comma, check https://stackoverflow.com/a/57734760/5640517