Python Forum
tuple and formating problem - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: tuple and formating problem (/thread-16177.html)



tuple and formating problem - darktitan - Feb-17-2019

Hi
Im using sqlite3 for a lite project and im getting this error

Error:
conn.execute('SELECT * FROM anställda WHERE ID={0},{1},{2},{3}'.format(uid[:4])) IndexError: tuple index out of range
i have no idea how to fix it. I think the fault lies in the formating or something. Could anyone take a look at the code and help pls.

    # Database  stuff
    #dataid = (uid[:4])
    conn.execute('SELECT * FROM anställda WHERE ID={0},{1},{2},{3}'.format(uid[:4]))
    data = cursor.fetchall()
    #print(data)
    for row in data:
        version = (row[0]) #<----siffran bestämmer column
        print(version)



RE: tuple and formating problem - marienbad - Feb-17-2019

sql = "SELECT * FROM anställda WHERE ID = ?"
data = (uid[:4],) # you need the comma as it expects a tuple!

conn.execute(sql, data)

does this work? I am unsure how uid is used and why you have 4 values in the "Where" part.


RE: tuple and formating problem - darktitan - Feb-17-2019

Hey
The uid is a rfid tag code when i read the tag i get a nummber like this 150, 110, 1, 164 .
So what im trying to do is to scan the tag and then look up the nummber in the database.

Here is how i do it when im not using a db.

    # UID stuff
    if status == MIFAREReader.MI_OK:
     # Print UID
      print "Card read UID: {0},{1},{2},{3}".format(*uid)
      print (st)
      if uid[:4] == [150,110,1,164]:
        Print ("Hi there")
      time.sleep(2)



RE: tuple and formating problem - marienbad - Feb-17-2019

How is the uid stored in the database? is it one column of varchar, or four separate numbers?


RE: tuple and formating problem - darktitan - Feb-17-2019

Its stored in one column of TEXT.


RE: tuple and formating problem - marienbad - Feb-17-2019

If it is in the same form as "150, 110, 1, 164":

(assumes uid is a string)

sql = "SELECT * FROM anställda WHERE ID = ?"
data = (uid,) # you need the comma as it expects a tuple!

conn.execute(sql, data)

Does this work?


RE: tuple and formating problem - darktitan - Feb-17-2019

I dont understand the code you wrote.


RE: tuple and formating problem - marienbad - Feb-17-2019

Okay, so the uid is a list of numbers, right? In which case we need to make them a string and check it against the db, so to adjust the above code:

for e.g. uid = [150,110,1,164]

uid_str = ','.join([str(i) for i in uid])

then we create the sql for the query:

sql_str = "SELECT * FROM anställda WHERE ID = ?"

and the data for the query is now the uid_str we created from the list of numbers (i.e. "150,110,1,64"

so we use that as the data and pass it to the execute function:

conn.execute(sql_str, uid_str)