Python SQL query string formatting

后端 未结 10 1520
没有蜡笔的小新
没有蜡笔的小新 2020-12-04 08:51

I\'m trying to find the best way to format an sql query string. When I\'m debugging my application I\'d like to log to file all the sql query strings, and it is important t

10条回答
  •  一个人的身影
    2020-12-04 09:20

    Sorry for posting to such an old thread -- but as someone who also shares a passion for pythonic 'best', I thought I'd share our solution.

    The solution is to build SQL statements using python's String Literal Concatenation (http://docs.python.org/), which could be qualified a somewhere between Option 2 and Option 4

    Code Sample:

    sql = ("SELECT field1, field2, field3, field4 "
           "FROM table "
           "WHERE condition1=1 "
           "AND condition2=2;")
    

    Works as well with f-strings:

    fields = "field1, field2, field3, field4"
    table = "table"
    conditions = "condition1=1 AND condition2=2"
    
    sql = (f"SELECT {fields} "
           f"FROM {table} "
           f"WHERE {conditions};")
    

    Pros:

    1. It retains the pythonic 'well tabulated' format, but does not add extraneous space characters (which pollutes logging).
    2. It avoids the backslash continuation ugliness of Option 4, which makes it difficult to add statements (not to mention white-space blindness).
    3. And further, it's really simple to expand the statement in VIM (just position the cursor to the insert point, and press SHIFT-O to open a new line).

提交回复
热议问题