我希望使用多台计算机来运行 python 脚本。我想将 mysql 中的唯一数据提供给运行脚本的每台计算机。我有一个半工作的解决方案,但问题是当两个脚本同时运行它时,在任何一个脚本可以将状态列更新为“处理”之前,它将选择相同的数据。
我已经尝试过:
"SELECT * FROM table WHERE status IS NULL FOR UPDATE"
但这似乎将我的第二个连接完全锁定在数据库之外,不允许它获取下面的数据进行处理。
我还尝试了下面的代码,它可以工作,但前提是两个脚本不同时尝试访问数据库。
vids = []
ids = []
c.execute('SELECT video_id,url FROM videos WHERE status IS NULL LIMIT 100;')
data = c.fetchall()
for row in data:
vids.append((row[1],row[0]))
ids.append(row[0])
c.executemany('UPDATE videos SET status="processing" WHERE video_id=%s;', ids)
db.commit()
我希望每台计算机都能获取独特的数据集进行处理。脚本1抓取1-100,脚本2抓取101-200,脚本3抓取201-300,等等
感谢您的帮助!祝你有美好的一天!
最佳答案
这是我的建议
你可以使用mysql lock tables ,但您需要将查询更新为:
c.execute('lock tables videos; UPDATE videos SET status="processing" WHERE video_id in (select t1.video_id from (select video_id, row_number() over (order by video_id) as rn from videos where coalesce(status, '') = '') as t1 where rn <= 100); unlock tables;')
此解决方案仅适用于mysql versionn 8.0
以上。
你不需要 for 循环。
关于mysql - 如何将 SQL Server 中的唯一数据划分到两台不同的计算机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58513859/