Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

    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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading