2017-10-12 73 views
-1

我很困惑我如何在Python中進行編碼。如何編碼sql選擇字符串

以下代碼來自pgsql命令行。

select * from consultation_tbl where consultation_status in ('S','C','R'); 

但在Python中,我不知道如何編碼。

chat_str = "\'S\',\'C\',\'R\'" 
cursor.execute(" \ 
     SELECT * FROM consultation_tbl 
     WHERE consultation_status IN (%s)", [chat_str]) 

請給我一個建議。

+1

字符串替換可能導致SQL注入攻擊。 – lad2025

+0

[python中的變量與SQL查詢]可能的重複(https://stackoverflow.com/questions/23217680/sql-query-with-variables-in-python) – wwii

回答

1

首先,你可以使用雙引號字符串中的單引號,這是一個有效的Python文本字符串:

chat_str = "'S', 'C', 'R'" 

但我會像代碼這:

# 1) This joins the tokens with ', ' separator. Very useful 
chat_str = ', '.join(["'S'", "'C'", "'R'",]) 

# 2) We use the python3 format() method for strings. 
# The '{}' is replaced. See the official docs 
query = "SELECT * FROM consultation_tbl 
    WHERE consultation_status IN ({})".format(chat_str) 

cursor.execute(query) 

在這兩種情況下,結果字符串是等效的。

+0

謝謝你的建議。但我有以下錯誤。 'django.db.utils.ProgrammingError:column「s」does not exist LINE 1:... ation_tbl WHERE consultation_status IN(S,C,R)'我該如何解決它? –

+0

您好像在代碼中有%s,而不是{}佔位符 – madtyn

+0

非常感謝您的回覆。我在我的代碼中使用{}。我複製你的代碼並粘貼它。哪裏不對? –

0

通常,您不希望將數據插入到使用手動sting替換的查詢中 - python sql api允許您傳遞一個元組,它將清理併爲您阻止sql注入。這是因爲IN子句中的parms列表的長度可以是動態的,所以您可能仍然需要字符串替換來創建模板查詢。我平時已經看到了這個樣子:

char_list = ['S', 'C', 'R' ] 
qry = "SELECT * FROM consultation_tbl WHERE consultation_status IN (%s)" 
qry %= ",".join("%s" for x in range(len(char_list))) 

cursor.execute(qry, chars) 
+0

謝謝你的建議。 chars從哪裏來? –