我有一个名为“未处理”的表,我想读取 2000 行,通过 HTTP 将它们发送到另一台服务器,然后将这些行插入“已处理”表并将它们从“未处理”表中删除。
我的python代码大致是这样的:
db = MySQLdb.connect("localhost","username","password","database" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Select all the records not yet sent
sql = "SELECT * from unprocessed where SupplierIDToUse = 'supplier1' limit 0, 2000"
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
id = row[0]
<code is here here for sending to other server - it takes about 1/2 a second>
if sentcorrectly="1":
sql = "INSERT into processed (id, dateprocessed) VALUES ('%s', NOW()')" % (id)
try:
inserted = cursor.execute(sql)
except:
print "Failed to insert"
if inserted:
print "Inserted"
sql = "DELETE from unprocessed where id = '%s'" % (id)
try:
deleted = cursor.execute(sql)
except:
print "Failed to delete id from the unprocessed table, even though it was saved in the processed table."
db.close()
sys.exit(0)
我希望能够同时运行此代码,以便提高通过 HTTP 将这些记录发送到其他服务器的速度。目前,如果我尝试同时运行代码,我会在另一个服务器上发送相同数据的多个副本并保存到“已处理”表中,因为选择查询在代码的多个实例中获得相同的 id。
如何在选择记录时锁定记录,然后将每条记录作为一行处理,然后再将它们移动到“已处理”表?该表是 MyISAM,但我今天已转换为 innoDB,因为我意识到可能有一种方法可以更好地使用 innoDB 锁定记录。