结合以下观点:
Levon或Jesse、Faheel和ddrscott
根据我的格式建议,您可以将查询写成:
query = ('SELECT'
' action.descr as "action"'
',role.id as role_id'
',role.descr as role'
' FROM'
' public.role_action_def'
',public.role'
',public.record_def'
',public.action'
' WHERE'
' role.id = role_action_def.role_id'
' AND'
' record_def.id = role_action_def.def_id'
' AND'
' action.id = role_action_def.action_id'
' AND'
' role_action_def.account_id = ?' # account_id
' AND'
' record_def.account_id = ?' # account_id
' AND'
' def_id = ?' # def_id
)
vars = (account_id, account_id, def_id) # A tuple of the query variables
cursor.execute(query, vars) # Using Python's sqlite3 module
或类似:
vars = []
query = ('SELECT'
' action.descr as "action"'
',role.id as role_id'
',role.descr as role'
' FROM'
' public.role_action_def'
',public.role'
',public.record_def'
',public.action'
' WHERE'
' role.id = role_action_def.role_id'
' AND'
' record_def.id = role_action_def.def_id'
' AND'
' action.id = role_action_def.action_id'
' AND'
' role_action_def.account_id = '
vars.append(account_id) or '?'
' AND'
' record_def.account_id = '
vars.append(account_id) or '?'
' AND'
' def_id = '
vars.append(def_id) or '?'
)
cursor.execute(query, tuple(vars)) # Using Python's sqlite3 module
与“IN”和“vars.extend(options)”或“n_options(len(option))”一起使用可能很有趣,其中:
def n_options(count):
return '(' + ','.join(count*'?') + ')'
或者从darkcaline那里得到的提示是,您可能仍然会在使用前导空格和分隔符以及命名占位符时出错:
SPACE_SEP = ' '
COMMA_SEP = ', '
AND_SEP = ' AND '
query = SPACE_SEP.join((
'SELECT',
COMMA_SEP.join((
'action.descr as "action"',
'role.id as role_id',
'role.descr as role',
)),
'FROM',
COMMA_SEP.join((
'public.role_action_def',
'public.role',
'public.record_def',
'public.action',
)),
'WHERE',
AND_SEP.join((
'role.id = role_action_def.role_id',
'record_def.id = role_action_def.def_id',
'action.id = role_action_def.action_id',
'role_action_def.account_id = :account_id',
'record_def.account_id = :account_id',
'def_id = :def_id',
)),
))
vars = {'account_id':account_id,'def_id':def_id} # A dictionary of the query variables
cursor.execute(query, vars) # Using Python's sqlite3 module
请参阅Cursor.execute-function的文档。
“这是[最Python]的方式!”-。。。