Zaid
Zaid

Reputation: 69

Tuple returned from sql can't be converted to int

i am trying to get the last value of the id from the SQL table, but it returns tuple and i am struggling to concatenate to an int in order to pass the value to the other methods,

Example of the method:

def generateId(myConnection):
    with myConnection:
        cur = myConnection.cursor()
        cur.execute(" select max(id) from images")
        id = cur.fetchall()
    myConnection
    print id         # returns ((43L,),)
    newId = int(id) + 1


    return newId

The error:

<ipython-input-1-9955a4d0f492> in generateId(myConnection)
     30     myConnection
     31     print id
---> 32     newId = int(id) + 1
     33 
     34 

TypeError: int() argument must be a string or a number, not 'tuple'

If you have any further questions regarding my database or method, please let me know, Thank you in advance

Upvotes: 0

Views: 142

Answers (3)

The
The

Reputation: 246

.fetchall returns all (remaining) rows as a sequence of sequences. You can retrieve the first (and in your case, the only) row of the result with cur.fetchone()[0]. Consequently, the value in the first (again, also the only) field of the first row can be retrieved as id = cur.fetchone()[0][0].

Upvotes: 1

Nannan AV
Nannan AV

Reputation: 419

You can either use cur.fetchone() or you can use int(id[0][0])

Upvotes: 1

galmeriol
galmeriol

Reputation: 461

You can try assigning your id with following;

((id,),) = cur.fetchall()

Upvotes: 0

Related Questions