我正在使用 python 连接到 mysql 并将数据写入表。我有一个 while 循环,我在每个循环中用一些值更新表的一个特定行。然后在循环结束后,我提交执行。现在的问题是:我应该更新 5000 行数据,因为有 5000 个循环。但是,我只看到 1K 行或数据更新。以下是伪代码:
import pymysql
import pymysql.cursors
connection =pymysql.connect(
user='root',
host='localhost',
database='mysql')
mycursor=connection.cursor()
mycursor.execute('use test_db')
n=0
while n<5000:
id=IDlist[n]
url='www.example.com/'+str(id)
values=requests.get(url) ##some parse omitted
input=(values[1],values[2],id)
sql="""UPDATE mytable
SET COL1=%s, COL2=%s
WHERE ID=%s"""
mycursor.execute(sql, input)
connection.commit() ## here all loops done
表的结构如下:
[ID INT(5) NOT NULL,COL1 VARCHAR,COL2 MEDIUMBLOB]
其中列 ID 是主键
所以基本上我所做的是:我每次读取一个唯一 ID,转到相应的网页并读取一些数据值,然后将这些值写入与该唯一 ID 对应的行中。
我担心的是,是否有可能由于每次循环中要保存的数据相对较大(~500KB),所以在进行 connection.commit() 之前的 while 循环中丢失了一些数据?
如果是这种情况,那么我是否应该事先声明自动提交?但是,似乎在每次循环中插入/更新数据后立即执行自动提交会导致整个任务相对较慢。
最佳答案
考虑分解请求和 MySQL 更新。您可以在大型 input[]
列表中迭代附加列表。然后,遍历 input[]
。请注意,我将所有打开的数据库连接和游标都移到了最后,以最大限度地减少长连接时间。此外,您希望在每次执行后提交,因此提交应该在循环内。
import pymysql
# URL DATA
input = [] ## LIST OF LISTS
for id in IDlist:
url='www.example.com/'+str(id)
values=requests.get(url) ##some parse omitted
input.append([values[1],values[2],id])
# DATABASE UPDATE
connection = pymysql.connect(
host='localhost', db='test_db',
user='root', passwd='***')
mycursor = connection.cursor()
for items in input:
sql="""UPDATE mytable
SET COL1=%s, COL2=%s
WHERE ID=%s"""
mycursor.execute(sql, tuple(items))
connection.commit()
mycursor.close() ## here all loops done
connection.close() ## close db connection
关于python - Python : Only partial data was saved while循环更新数据到Mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33948006/