【发布时间】:2014-12-12 10:31:26
【问题描述】:
我为 SQLite 制作了一个小型的 sql 渲染器/包装器。主要思路是这样写:
execute( 'select * from talbe1 where col1={param1} and col2={param2}' )
而不是
execute( 'select * from table1 where col1=? and col2=?', (param1,param2) )
代码如下:
import re
import sqlite3
class SQLWrapper():
def __init__(self, cursor):
self.cursor = cursor
def execute(self, sql):
regexp=re.compile(r'\{(.+?)\}')
sqlline = regexp.sub('?',sql)
statements = regexp.findall(sql)
varlist = tuple([ eval(_statement) for _statement in statements ])
self.cursor.execute(sqlline, varlist)
return self
def fetchall(self):
return self.cursor.fetchall()
#usage example
db = sqlite3.connect(':memory:')
cursor = db.cursor()
wrap = SQLWrapper(cursor)
wrap.execute('create table t1(a,b)')
for i in range(10):
wrap.execute('insert into t1(a,b) values({i}, {i*2})')
limit = 50
for line in wrap.execute('select * from t1 where b < {limit}').fetchall():
print line
它可以工作,但是当我将类 SQLWrapper 移动到一个单独的模块(文件 sqlwrap.py)并导入它时,程序崩溃了:
Traceback (most recent call last):
File "c:\py\module1.py", line 15, in <module>
wrap.execute('insert into t1(a,b) values({i}, {i*2})')
File "c:\py\sqlwrap.py", line 10, in execute
varlist = tuple([ eval(_statement) for _statement in statements ])
File "<string>", line 1, in <module>
NameError: name 'i' is not defined
即变量 i 在其他模块中不可见。如何克服?
【问题讨论】:
标签: python sqlite namespaces eval