Note that there are some explanatory texts on larger screens.

plurals
  1. POPython SQL query string formatting
    primarykey
    data
    text
    <p>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.</p> <p><strong>Option 1</strong></p> <pre><code>def myquery(): sql = "select field1, field2, field3, field4 from table where condition1=1 and condition2=2" con = mymodule.get_connection() ... </code></pre> <ul> <li>This is good for printing the sql string.</li> <li>It is not a good solution if the string is long and not fits the standard width of 80 characters.</li> </ul> <p><strong>Option 2</strong></p> <pre><code>def query(): sql = """ select field1, field2, field3, field4 from table where condition1=1 and condition2=2""" con = mymodule.get_connection() ... </code></pre> <ul> <li><p>Here the code is clear but when you print the sql query string you get all these annoying white spaces.</p> <blockquote> <p>u'\nselect field1, field2, field3, field4\n_<strong><em>_</em>___</strong><em>from table\n</em><strong><em>_</em>___</strong><em>where condition1=1 \n</em><strong><em>_</em>___</strong>_and condition2=2'</p> </blockquote></li> </ul> <p><em>Note: I have replaced white spaces with underscore <code>_</code>, because they are trimmed by the editor</em></p> <p><strong>Option 3</strong></p> <pre><code>def query(): sql = """select field1, field2, field3, field4 from table where condition1=1 and condition2=2""" con = mymodule.get_connection() ... </code></pre> <ul> <li>I don't like this option because it breaks the clearness of the well tabulated code.</li> </ul> <p><strong>Option 4</strong></p> <pre><code>def query(): sql = "select field1, field2, field3, field4 " \ "from table " \ "where condition1=1 " \ "and condition2=2 " con = mymodule.get_connection() ... </code></pre> <ul> <li>I don't like this option because all the extra typing in each line and is difficult to edit the query also.</li> </ul> <p>For me the best solution would be <strong>Option 2</strong> but I don't like the extra whitespaces when I print the sql string.</p> <p>Do you know of any other options?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload