2016-06-23 24 views
2

我編寫了一個SQL查詢,它使用從WTForms傳入的數據作爲參數。 如何確保變量上的雙引號?如何確保多行字符串中的雙引號

q = """ 
select * from table 
where dt_date >= %(date)s""" % {'date':date} 

現在它顯示爲

select * from table 
where dt_date >= 23-06-2016 

然後拋出錯誤。如何使它變成:

select * from table 
where dt_date >= "23-06-2016" 
+0

你可以把字面雙引號到您的三重引號的字符串。 – khelwood

+0

它是否必須是雙引號或單引號才能起作用?如果單引號可以工作,我建議使用'%(date)r'而不是's'來獲取字符串的代碼表示(包括字符串引號) –

回答

0

Python不會阻止您在多行字符串中使用雙引號。麻煩只有當你把它們放在一起時("""")。您可以使用雙引號作爲\"或簡單地在它們和三重引號(" """)之間留出空格。

逃離:

q = """ 
select * from table 
where dt_date >= \"%(date)s\""""%{'date':date} 
>>> print q 

select * from table 
where dt_date >= "asdf" 

空間三重引號前:

q = """ 
select * from table 
where dt_date >= "%(date)s" """%{'date':date} 
>>> print q 

select * from table 
where dt_date >= "asdf" 
1

嘗試轉義多引號中的雙引號。

>>> q = """ 
... select * from table 
... where dt_date >= \"%(date)s\""""%{'date':date} 
>>> q 
'\nselect * from table\nwhere dt_date >= "23-06-2016"' 
>>> print q 

select * from table 
where dt_date >= "23-06-2016" 
相關問題