2013-10-19 52 views
2

我知道正確的方式,以避免在SELECT注入攻擊或INSERT使用Python模塊MySQLdb的疑問是:如何防止注入攻擊在Python中創建MySQL查詢

cursor.execute("SELECT spam, eggs, sausage FROM breakfast WHERE price < %s", (max_price,))

然而,當我試圖申請CREATE查詢中的相同規則會返回錯誤。我的代碼:

cursor.execute("CREATE DATABASE %s;", ("test",))

它報告語法錯誤:

_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''test'' at line 1")

現在看來,這是因爲該查詢增加了單引號的數據庫名稱和MySQL不允許在CREATE查詢?

那麼,使用python MySQLdb模塊來創建數據庫或表的正確方法是什麼?然後,給定db名稱或表名不固定?

+1

你真的需要一個參數化查詢嗎?根據用戶提供的數據創建整個表/數據庫有點不尋常。 – BrenBarn

+0

只需追加字符串:'cursor.execute(「CREATE DATABASE」+「test」)' – hjpotter92

+1

@ hjpotter92:好吧,或者只是首先使用一個字符串:'cursor.execute(「CREATE DATABASE test」)'。 – BrenBarn

回答

0

嘗試方括號;

cursor.execute("CREATE DATABASE %s;", ["test"])