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 that the string is properly formated.
Option 1
def myquery():
sql = "select field1, field2, field3, field4 from table where condition1=1 and condition2=2"
con = mymodule.get_connection()
...
- This is good for printing the sql string.
- It is not a good solution if the string is long and not fits the standard width of 80 characters.
Option 2
def query():
sql = """
select field1, field2, field3, field4
from table
where condition1=1
and condition2=2"""
con = mymodule.get_connection()
...
Here the code is clear but when you print the sql query string you get all these annoying white spaces.
u'\nselect field1, field2, field3, field4\n_____from table\n____where condition1=1 \n_____and condition2=2'
Note: I have replaced white spaces with underscore _
, because they are trimmed by the editor
Option 3
def query():
sql = """select field1, field2, field3, field4
from table
where condition1=1
and condition2=2"""
con = mymodule.get_connection()
...
- I don't like this option because it breaks the clearness of the well tabulated code.
Option 4
def query():
sql = "select field1, field2, field3, field4 " \
"from table " \
"where condition1=1 " \
"and condition2=2 "
con = mymodule.get_connection()
...
- I don't like this option because all the extra typing in each line and is difficult to edit the query also.
For me the best solution would be Option 2 but I don't like the extra whitespaces when I print the sql string.
Do you know of any other options?