我从How do I get a raw, compiled SQL query from a SQLAlchemy expression?获得了以下代码,它在我们从Python 2.7迁移到Python 3.4之前一直运行良好。我已经做了一些改变但是我坚持
return (comp.string.encode(enc) % params).decode(enc)
错误不支持操作数类型%:' bytes'和' dict'
def compile_query(query):
dialect = query.session.bind.dialect
statement = query.statement
comp = compiler.SQLCompiler(dialect, statement)
comp.compile()
enc = dialect.encoding
params = {}
for k,v in comp.params.iteritems():
if isinstance(v, unicode):
v = v.encode(enc)
params[k] = sqlescape(v)
return (comp.string.encode(enc) % params).decode(enc)
答案 0 :(得分:0)
感谢评论,我把它移植到python 3
def compile_query(query):
dialect = query.session.bind.dialect
statement = query.statement
comp = compiler.SQLCompiler(dialect, statement)
comp.compile()
enc = dialect.encoding
params = {}
for k,v in comp.params.items():
if isinstance(v, str):
v = v.encode(enc)
params[k] = sqlescape(v)
return (comp.string % params)