文章目录
我自己知道的,这类问题有两类原因,两种解决方案。
错误一
错误原因
pymysql的主进程启动的connect无法给子进程中使用,所以读取大批量数据时最后容易出现了此类问题。
解决方案
换成pymysql-pool可以解决方法:
具体如下:
shell
pip install pymysql-pool
代码如下:
python
import pymysql
import pymysqlpool
def select_ebay_catelotory():
config={'host': HOST, 'user': USER, 'password': PASSWD, 'database': DB, 'autocommit':True}
pool1 = pymysqlpool.ConnectionPool(size=10, maxsize=20, pre_create_num=2, name='pool1', **config)
con1 = pool1.get_connection()
gcu = con1.cursor()
try:
gcu.execute(f"""SELECT *** """)
# 获取剩余结果所有数据
rows = gcu.fetchall()
except Exception as e:
print(e)
finally:
# gcu.close()
con1.close()
return rows
错误二
原因
要读取的内容太大了。有两类:某列太长了,总行数太多了。
如何确定?
你的代码读取100行没问题,1000行也没问题,10000行也没问题,100万行就有问题了。那就是这个原因。
解决方案
不要limit去读,太费时间:先取id,再用id去分批读取数据。
python
import pymysql
import pymysqlpool
def select_all_ids():
config={'host': HOST, 'user': USER, 'password': PASSWD, 'database': DB, 'autocommit':True}
pool1 = pymysqlpool.ConnectionPool(size=35, maxsize=35, pre_create_num=2, name='pool1', **config)
con1 = pool1.get_connection()
gcu = con1.cursor()
try:
gcu.execute(f"""SELECT `id` FROM sfc_minesweeper.product_detail WHERE create_time>'2024-07-10' AND CHAR_LENGTH(result_data)>500""")
# 获取剩余结果所有数据
rows = gcu.fetchall()
except Exception as e:
print(e)
finally:
# gcu.close()
con1.close()
return rows
def select_ebay_catelotory(pids):
config={'host': HOST, 'user': USER, 'password': PASSWD, 'database': DB, 'autocommit':True}
pool1 = pymysqlpool.ConnectionPool(size=35, maxsize=35, pre_create_num=2, name='pool1', **config)
con1 = pool1.get_connection()
gcu = con1.cursor()
try:
gcu.execute(f"""SELECT `id`, `result_data`, `product_offer_id` FROM sfc_minesweeper.product_detail WHERE id in {tuple(pids)}""")
# 获取剩余结果所有数据
rows = gcu.fetchall()
except Exception as e:
print(e)
finally:
# gcu.close()
con1.close()
return rows
# 先拿到所有id
pd_ids = [e[0] for e in select_all_ids()]
# 再分批读取
pd1688s = []
step = 4000
for begin in range(0, len(pd_ids), step):
pd1688s.extend([e for e in select_ebay_catelotory(pd_ids[begin:begin+step])])
print(i, len(pd1688s))