开发者

Escaping queries in Django

开发者 https://www.devze.com 2023-02-14 22:25 出处:网络
I have the following method: def select_query(self): sql = \"SELECT * FROM {t} WHERE 1\".format(t=self._meta.db_table)

I have the following method:

def select_query(self):
    sql = "SELECT * FROM {t} WHERE 1".format(t=self._meta.db_table)
    for column_name in self.distinguishing_column_names():
        sql = sql + " AND {c} = {v}".format(c=column_name, v=getattr(self, column_name))
    return sql

This will give me a query like this:

SELECT * FROM customer WHERE 1 AND name = JOHN SMITH AND customer_number = 11423 AND social_security_number = 1234567890 AND phone开发者_JS百科 = 2323523353

Obviously, that's not going to work. Is there a way to get Django to quote this for me?

Note: I'm not asking for a prepared statement. That's something different.


Do you need to return a query this way? The proper way would be to call cursor with the query and the params as argument:

Does Python support MySQL prepared statements?

The correct way to format a query seems to be:

query = query % db.literal(args)

Where db is a mysql.Connection (or presumably any connection)


Apparently the answer is "no."

0

精彩评论

暂无评论...
验证码 换一张
取 消