Python SQL query string formatting

后端 未结 10 1517
没有蜡笔的小新
没有蜡笔的小新 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:30

    You've obviously considered lots of ways to write the SQL such that it prints out okay, but how about changing the 'print' statement you use for debug logging, rather than writing your SQL in ways you don't like? Using your favourite option above, how about a logging function such as this:

    def debugLogSQL(sql):
         print ' '.join([line.strip() for line in sql.splitlines()]).strip()
    
    sql = """
        select field1, field2, field3, field4
        from table"""
    if debug:
        debugLogSQL(sql)
    

    This would also make it trivial to add additional logic to split the logged string across multiple lines if the line is longer than your desired length.

提交回复
热议问题