title: How to copy database from MySQL to another database using different python services, ensuring that a row gets copied only once?
body: <p>I have a database called tbltest which has 4 columns : Id, Fname, Lname, Iscategorized. I have to copy the data from its first three columns to another database tblcopy which has 4 columns: Id, Fname, Lname, Service_number. I copy the data only when Iscategorized is 0 and after copying, I update it to 1. The Service column tells the python service which is copying the data. Follwing is the code I use for copying using service 1.</p>
  
  <pre><code>import time
  var = True
  while var == True:
      #!/usr/bin/python
      import MySQLdb
      # Open database connection
      db = MySQLdb.connect("localhost","root","amanbaweja","test" )
      # prepare a cursor object using cursor() method
      cursor = db.cursor()
  
      sql = "SELECT * FROM tbltester\
         WHERE iscategorized = '%d'" % (0) + " limit 0,1 " 
      # Execute the SQL command
      cursor.execute(sql)
      # Fetch all the rows in a list of lists.
      results = cursor.fetchall()
      for row in results:
          id = row[0]
          fname = row[1]
          lname = row[2]
          iscategorized = row[3]
                  # Now print fetched result
          print "id=%s,fname=%s,lname=%s,iscategorized=%s" % \
                   (id, fname, lname, iscategorized)
  
          cursor.execute('''INSERT into tblcopy (Id, Fname, Lname, Service_number) values(%s, %s, %s, %s)''',(id, fname, lname, "service1"))
          sql1 = "UPDATE tbltester SET iscategorized = 1 WHERE Id = '%s'" % id
          cursor.execute(sql1)
          db.commit()
      db.close()
  </code></pre>
  
  <p>Now as my database is dynamically getting bigger and bigger, I am using multiple machines to run my python services. The python services are running together using <em>supervisor</em>. If I run 10 services with the above mentioned code,approximately 5 different entries get created in tblcopy as 5 python services get the same id at once. Is there any SQL method to solve my problem? Can we do this using stored procedure?</p>
  
  <p>Thanks for your help in advance.</p>