你好,我試圖在Django中使用mysql準備語句。Django的mysql準備語句
我做了以下類:
class PreparedStatement(object):
def __init__(self,name,query):
self.name = name
self.query = query
self.vars = []
self.prepare()
def setVar(self,name,var):
name = "@%s" % name
if name not in self.vars:
self.vars.append(name)
SQL = "SET %s = " % (name)
self.__executeQuery(SQL+" %s;",var)
def prepare(self):
SQL = "PREPARE %s FROM " % self.name
self.__executeQuery(SQL + " %s ;", self.query)
def execute(self):
SQL = "EXECUTE %s " % self.name
if len(self.vars):
params = ""
for var in self.vars:
params += var + ", "
params = params[:-2]
SQL += "USING %s " % params
result = self.__executeQuery(SQL)
self.vars = []
return result
def __executeQuery(self,query,*args):
cursor = connection.cursor()
if args:
cursor.execute(query,args)
else:
cursor.execute(query)
return cursor
我用這樣的:
getDiscountsById = PreparedStatement("getDiscountsById","""SELECT * FROM table
WHERE id = ? LIMIT 1""")
getDiscountsById.setVar("id",5)
result = getDiscountsById.execute()
它的第一個加載的頁面工作正常,但更改URL或重裝編寫網頁的MySQL返回後聲明未找到錯誤。
問題出在哪裏?有沒有解決方法?
感謝響應和對不起我的英語:d
你爲什麼要使用預處理語句?它是爲了性能優勢,還是在不暴露SQL注入泄露的情況下編寫原始SQL? – Thomas
@Thomas 這是學校派遣,我不能使用ORM,我必須使用準備好的語句 – ChuckBorris