我为SQLite做了一个很小的sql渲染器/包装器。主要的想法是写:如何访问从Python中的调用模块调用模块名称空间?
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.e.变量i在其他模块中不可见。如何克服这一点?