2014-05-01 22 views
1

格式化字符串我有這兩個領域不能與列表

s = "SELECT * FROM %s WHERE %s = %s ORDER BY %s;" 
data = ['students', 'age', 12, 'desc'] 

從我所看到的,我計算列表足夠的元素來格式化字符串。 但

print s.format(data) 
#or 
print s % tuple(data) 
#or 
print s % data 

回報TypeError: not enough arguments for format string

+3

注意,它通常不使用字符串格式化來構建SQL語句是個好主意。相反,當你去執行你的查詢時,將你的數據作爲參數傳遞。這將允許數據庫轉義任何特殊字符,這將幫助您避免[SQL注入攻擊](http://xkcd.com/327/)。 – Blckknght

回答

2

只需將列表轉換爲元組,這樣

s, l = "SELECT * FROM %s WHERE %s = %s ORDER BY %s;",['students','age',12,'desc'] 
print s % tuple(l) 
# SELECT * FROM students WHERE age = 12 ORDER BY desc; 

Online Demo

+0

我已經試過了。請再次閱讀該問題。 – Saphire

+0

@Saphire你編輯過的版本實際上工作 – thefourtheye

+0

@Saphire我現在還包括一個在線演示。請檢查一下。 – thefourtheye