简体   繁体   中英

selecting from a list in SQL and python

I need help with the following scenario:

in my database file I have a table who looks something like this

https://i.stack.imgur.com/dCMwJ.png

I want to get a list of all the IDs that have suppliers_id=(2,3) (list of ids)

the problem is that I don't know which values are in the group (I'm getting the list in the function header from other SELECT function)

We were taught that we can use IN option that should get me the result I want but I cant getting it to work

my code (doesn't work for now):

    def update(self, suppliers_id):
        c = self._conn.cursor()
        c.execute("""SELECT id FROM Vaccines WHERE supplier_id IN (?)""", [suppliers_id])

I'm getting sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type. error

Thanks!

If you want to select multiple values from table, you've to add it as a tuple without assigning it to a new memory address.

By assigning your variable as a list, you're assigning it to a new memory address which is insufficient way of using Parameters Substitution .

Code Syntax

def update(self, suppliers_id):
    c = self._conn.cursor()
    c.execute("""SELECT id FROM Vaccines WHERE supplier_id IN (?)""", supplier_id, )   # by adding only comma, you're accessing the tuple, iteratively.

You pass a tuple inside existing parenthesis in your sql query, this results to IN ((some items)) which is not readable from sql. Try this instead (removed parenthesis and also change suppliers_id to tuple in case that it is a list):

def update(self, suppliers_id):
    c = self._conn.cursor()
    c.execute("""SELECT id FROM Vaccines WHERE supplier_id IN (?)""", [','.join(str(i) for i in suppliers_id)])

Two Options:

Either remove parenthesis from your sql query. For eg

def update(self, suppliers_id):
    c = self._conn.cursor()
    c.execute("""SELECT id FROM Vaccines WHERE supplier_id IN ?""", tuple(suppliers_id))

Or use format. For eg

def update(self, suppliers_id):
    c = self._conn.cursor()
    c.execute("""SELECT id FROM Vaccines WHERE supplier_id IN {}""".format(tuple(suppliers_id)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM