title: Getting value from MySQL and loop over it with if
body: <p>I have the following piece of code:</p>
  
  <pre><code>### Write the new userid to the sql database
  # Open database connection
  db = MySQLdb.connect("sql01.domain1.lan","webuserid","test","webuserid" )
  # prepare a cursor object using cursor() method
  cursor = db.cursor()
  
  
  
  dub_userid = int(userid)
  # Check for dublicate of current userid value
  sql = "SELECT * FROM webuserid WHERE userid = '"+str(dub_userid)+"'"
  try:
          # Execute the SQL command
          cursor.execute(sql)
          # Fetch all the rows in a list of lists.
          results = cursor.fetchone()
          data = cursor.fetchone()
  except:
          print "SQL Error: Unable to fetch data"
  if data == None:
          print "User doesn't exist - Creating"
  else:
          sys.exit("User exists")
  
  # Prepare SQL query to INSERT a record into the database.
  sql = """INSERT INTO webuserid(userid)
           VALUES ('"""+userid+"""')"""
  try:
          # Execute the SQL command
          cursor.execute(sql)
          # Commit your changes in the database
          db.commit()
  except:
          #Rollback in case there is any error
          db.rollback()
  # disconnect from server
  db.close()
  </code></pre>
  
  <p>The variable userid has a string value of 00001</p>
  
  <p>What I want the code to do, is connect to the database (works), convert userid to a integer in dub_userid, and use the resulting value to look for a dublicate.</p>
  
  <p>Problem is, that when I run the code, and, with userid value of 00001 the following happens:</p>
  
  <ol>
  <li>Userid 1 is commited to the database (As it should, since there's no other userid called 1</li>
  <li>Next run, userid 1 is commited to the database again (It shouldn't, since userid 1 already exists)</li>
  <li>Third run, the scripts exists with the "User exists" message as it should.</li>
  </ol>
  
  <p>I've tried both with data and data[1], but can't seem to figure out what's wrong.</p>