Pythonic way to create a long multi-line string

后端 未结 27 1651
滥情空心
滥情空心 2020-11-22 00:47

I have a very long query. I would like to split it in several lines in Python. A way to do it in JavaScript would be using several sentences and joining them with a +<

27条回答
  •  被撕碎了的回忆
    2020-11-22 01:03

    I personally find the following to be the best (simple, safe and Pythonic) way to write raw SQL queries in Python, especially when using Python's sqlite3 module:

    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 = ?
            AND record_def.account_id = ?
            AND def_id = ?
    '''
    vars = (account_id, account_id, def_id)   # a tuple of query variables
    cursor.execute(query, vars)   # using Python's sqlite3 module
    

    Pros

    • Neat and simple code (Pythonic!)
    • Safe from SQL injection
    • Compatible with both Python 2 and Python 3 (it's Pythonic after all)
    • No string concatenation required
    • No need to ensure that the right-most character of each line is a space

    Cons

    • Since variables in the query are replaced by the ? placeholder, it may become a little difficult to keep track of which ? is to be substituted by which Python variable when there are lots of them in the query.

提交回复
热议问题