如何在Python中返回多行SQL查询?兼容Python2与Python3
解决方案
1. 用三重引号定义多行SQL(最直观)
Python2和3都支持三重单/双引号的多行字符串,直接把SQL拆成多行编写即可,配合shlex.quote自动处理引号冲突,避免shell解析错误:
def get_query_cmd(): sql_query = '''select val1 from table_name where val2 = ( select val3 from another_table where val = 'abc' )''' import shlex quoted_sql = shlex.quote(sql_query) return "usr/<path> -e {}".format(quoted_sql)
2. 字符串拼接(传统写法)
如果偏好逐行拼接,用+连接每行,注意末尾的反斜杠(可选,用于视觉对齐)和内部单引号转义:
def get_query_cmd(): sql_query = 'select val1 ' + \ 'from table_name ' + \ 'where val2 = (' + \ ' select val3 ' + \ ' from another_table ' + \ ' where val = \'abc\' ' + \ ')' import shlex quoted_sql = shlex.quote(sql_query) return "usr/<path> -e {}".format(quoted_sql)
3. 列表拼接后join(易维护)
把SQL拆成列表元素,最后用空格连接,适合复杂SQL的分段管理:
def get_query_cmd(): sql_lines = [ 'select val1', 'from table_name', 'where val2 = (', ' select val3', ' from another_table', ' where val = \'abc\'', ')' ] sql_query = ' '.join(sql_lines) import shlex quoted_sql = shlex.quote(sql_query) return "usr/<path> -e {}".format(quoted_sql)
关键注意事项
- 必须处理引号冲突:SQL内部的单引号要么手动转义为
\',要么用shlex.quote自动处理,防止shell解析时语法报错。 - SQL的换行在shell中会被视为空格,不影响查询执行,无需额外处理。
- 以上三种写法均同时兼容Python2和Python3,无需版本判断。
内容的提问来源于stack exchange,提问作者pranami
相关产品推荐
相关产品推荐

