通过python,连接 数据库, 对其中 表进行 批次 循环 更新数据
导入包
import csv
import os
import re
import traceback
from datetime import datetime
from itertools import islice
import pymysql
import xlrd
from dbutils.pooled_db import PooledDB
from numpy import double
连接数据库
连接数据库配置
__config = {
"host": "11.11.11.11",
"port": 3306,
"user": "name1",
"password": "110",
"database": "data1"
}
设置连接池
POOL = PooledDB(
pymysql, 5, # 连接池里的最少连接数
**__config,
setsession=['SET AUTOCOMMIT = 1'] # 设置线程池是否打开自动更新的配置
)
提前备好sql语句
和需要分批处理的次数
size = 500 # 500次处理一下
针对的更新表 T1
针对T1表中,的C字段进行更新
选取A 和 B这两个字段作为 匹配条件
sql_1 = "SELECT A,B from T1 WHERE C is null order by A limit " + str(
size)
sql_2 = "SELECT A,B from T1 WHERE C is null and A > %s order by a limit %s"
针对的需要更新的数据来源 T2表
因为要更新C字段,在T2中提取出该字段
条件是依据A字段,所以也要在T2中的条件where中写出 字段A,但是字段A是
从T1中选出来的一个一个的循环提出出来的,所以用 %s替代
force_sql = "select C from T2 where A =%s"
更新语句,当从T2中提出 需要更新的C字段后,将其通过UPDATE语句
更新到T1中取,当然条件仍然是A字段
update_sql = "UPDATE T1 set C =%s where A = %s"
def update():
connection = POOL.connection() # 连接
cursor = connection.cursor()
cursor.execute(sql_1) # T1提取出需要更新的字段C,记得C是空,要的是A字段
A_B_All = cursor.fetchall() # 将提取出的全存到A_ALL中
while True:
for value in A_B_All: # 遍历 导出每个A和B
try:
A = value[0] # 提取A
B = value[1] # 提取B
cursor.execute(force_sql,[A]) # 依据A作为条件,在T2表中,找到对应需要更新到T1中的C
C_ALL = fetchall()# 提取所有的C
C = None # 设置一个初始值C为0
for C in C_ALL:
C=C[0] # C可能是个元组,只需要第一个
if C is not None: # C 不是空置,再更新其到T1中
cursor.execute(update_sql,[C,A]) # 更新T1中的C字段,条件是其A等于本次遍历的A值
count = count + 1 #处理了次数加1个
except:
print(A) # 打印出出错的A
traceback.print_exc() # 打印出报错原因
if len(A_B_ALL) == size: # 上面500次循环结束,判断一下是500次么
new = A_B_All[size-1][0] # 开启新的循环点
cursor.execute(sql_2,[new,size]) # 新点开始循环500次
cursor.execute = cursor.fetchall() # 提取新的500个数据
else:
break # 当最后一次500个不够数了,就跳出循环
cursor.close()
connection.close()
print("结束")
if __name__ == "__main__":
update()
print("结束")