由于音量的原因,我想分批制作这个过程.
这是我的代码:
getconn = conexiones()
con = getconn.mysqlDWconnect()
with con:
cur = con.cursor(mdb.cursors.DictCursor)
cur.execute("SELECT id, date, product_id, sales FROM sales")
rows = cur.fetchall()
Run Code Online (Sandbox Code Playgroud)
如何实现索引以批量获取数据?
bru*_*ers 29
第一点:python db-api.cursor
是一个迭代器,所以除非你真的需要一次在内存中加载一个完整的批处理,你可以从使用这个功能开始,即代替:
cursor.execute("SELECT * FROM mytable")
rows = cursor.fetchall()
for row in rows:
do_something_with(row)
Run Code Online (Sandbox Code Playgroud)
你可以这样:
cursor.execute("SELECT * FROM mytable")
for row in cursor:
do_something_with(row)
Run Code Online (Sandbox Code Playgroud)
然后,如果您的数据库连接器的实现仍未正确使用此功能,则可以将LIMIT和OFFSET添加到混合中:
# py2 / py3 compat
try:
# xrange is defined in py2 only
xrange
except NameError:
# py3 range is actually p2 xrange
xrange = range
cursor.execute("SELECT count(*) FROM mytable")
count = cursor.fetchone()[0]
batch_size = 42 # whatever
for offset in xrange(0, count, batch_size):
cursor.execute(
"SELECT * FROM mytable LIMIT %s OFFSET %s",
(batch_size, offset))
for row in cursor:
do_something_with(row)
Run Code Online (Sandbox Code Playgroud)
您可以使用
SELECT id, date, product_id, sales FROM sales LIMIT X OFFSET Y;
Run Code Online (Sandbox Code Playgroud)
其中X是所需批处理的大小,Y是当前偏移量(例如,X乘以当前迭代次数)
归档时间: |
|
查看次数: |
11150 次 |
最近记录: |