Python SQL query string formatting

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

    sql = ("select field1, field2, field3, field4 "
           "from table "
           "where condition1={} "
           "and condition2={}").format(1, 2)
    
    Output: 'select field1, field2, field3, field4 from table 
             where condition1=1 and condition2=2'
    

    if the value of condition should be a string, you can do like this:

    sql = ("select field1, field2, field3, field4 "
           "from table "
           "where condition1='{0}' "
           "and condition2='{1}'").format('2016-10-12', '2017-10-12')
    
    Output: "select field1, field2, field3, field4 from table where
             condition1='2016-10-12' and condition2='2017-10-12'"
    

提交回复
热议问题