【发布时间】:2014-02-01 07:19:06
【问题描述】:
我正在尝试遍历 SQLite 数据库并对列表中的对象执行检查或操作。我需要使用数据库,因为最终的对象数量会非常大,而且所有操作本质上都是串行的(在基本排序之后)。
我的问题是如何遍历列表并在检查对象的某些品质后将其放入新的数据库对象中?我想执行几次串行“检查”,一次最多将两个对象带入内存,然后重新分配。
以下是我的代码示例。当我运行最后一个操作时,我无法“重新运行”同一个循环。我怎样才能不只是打印对象,而是将其保存到新数据库中?
import os
import sqlite3 as lite
import sys
import random
import gc
import pprint
def make_boxspace():
refine_zone_cube_size = 1
refine_zone_x1 = 1*refine_zone_cube_size
refine_zone_y1 = 1*refine_zone_cube_size
refine_zone_z1 = 1*refine_zone_cube_size
refine_zone_x2 = refine_zone_x1+(2*refine_zone_cube_size)
refine_zone_y2 = refine_zone_y1+(1*refine_zone_cube_size)
refine_zone_z2 = refine_zone_z1+(1*refine_zone_cube_size)
point_pass_length = (1.0/4.0)
outlist = []
for i in range(int((refine_zone_x2-refine_zone_x1)/point_pass_length)):
for j in range(int((refine_zone_y2-refine_zone_y1)/point_pass_length)):
for k in range(int((refine_zone_z2-refine_zone_z1)/point_pass_length)):
if (random.random() > 0.5):
binary = True
else:
binary = False
if binary:
x1 = point_pass_length*i
y1 = point_pass_length*j
z1 = point_pass_length*k
x2 = x1+point_pass_length
y2 = y1+point_pass_length
z2 = z1+point_pass_length
vr_lev = int(random.random()*3)
outlist.append([\
float(str("%.3f" % (x1))),\
float(str("%.3f" % (y1))),\
float(str("%.3f" % (z1))),\
float(str("%.3f" % (x2))),\
float(str("%.3f" % (y2))),\
float(str("%.3f" % (z2))),\
vr_lev
])
return outlist
### make field of "boxes"
boxes = make_boxspace()
### define database object and cursor object
box_data = lite.connect('boxes.db')
cur = box_data.cursor()
### write the list in memory to the database
cur.execute("DROP TABLE IF EXISTS boxes")
cur.execute("CREATE TABLE boxes(x1,y1,z1,x2,y2,z2,vr)")
cur.executemany("INSERT INTO boxes VALUES(?, ?, ?, ?, ?, ?, ?)", boxes)
### clear the 'boxes' list from memory
del boxes
### re-order the boxes
cur.execute("SELECT * FROM boxes ORDER BY z1 ASC")
cur.execute("SELECT * FROM boxes ORDER BY y1 ASC")
cur.execute("SELECT * FROM boxes ORDER BY x1 ASC")
### save the database
box_data.commit()
### print each item
while True:
row = cur.fetchone()
if row == None:
break
print(row)
谢谢大家!!!
【问题讨论】:
-
这不是您的代码示例,这是整个代码:p
-
假设这是一个“精简版”哈哈:D
-
当我运行这段代码时,它会在我的硬盘上创建一个名为 box.db 的新 sqlite3 数据库,里面装满了“盒子”......什么不工作?
-
您可能需要考虑使用ORM,例如SQLAlchemy。除了提供更直观的数据库接口外,它的优点是对数据库引擎(sqlite)进行了抽象,以后如果需要可以使用其他的(postgresql、mysql、...)
-
备份一秒钟。您想要数据库表
boxes的样子,还是最终目标是对boxes中的元素重新排序?
标签: python sqlite python-3.x