python & Mysql: unsupported operand type(s) for -: 'int' and 'tuple'

I would like to fetch a record from a table and put it in the variable "gl". if value is bigger or smaller then value+-gl it should write into the database

import MySQLdb
import time
import string


while True:
  db = MySQLdb.connect(host="10.0.0.100", port=3306, user="ubuntu", passwd="ubuntu", db="test")
  cursor = db.cursor()
  cursor.execute("SELECT glaettung FROM ttable ORDER BY id DESC LIMIT 1")
  gl = cursor.fetchall()
  print gl
  value = (20)
  if (value < (value-gl)):
    cursor = db.cursor()
    cursor.execute("INSERT INTO ttable (value) VALUES(%s)", (value))
  elif (value > (value+gl)):
    cursor = db.cursor()
    cursor.execute("INSERT INTO ttable (value) VALUES(%s)", (value))
  else:
    print "Done"

This is the error:

ubuntu@ubuntu-Aspire-6920:~/Dokumente$ python test.py 
(('2',),)
Traceback (most recent call last):
  File "test.py", line 13, in <module>
    if (value < (value-gl)):
TypeError: unsupported operand type(s) for -: 'int' and 'tuple'

Upvotes: 2

Views: 18851

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250871

gl is a tuple, to access '2' inside it you need to use indexing and then call int() on it get an integer:

>>> gl = (('2',),)
>>> gl[0][0]
'2'

So, instead of using gl directly, use:

>>> int(gl[0][0])
2

Upvotes: 1

Related Questions