简体   繁体   中英

Escaping queries in Django

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 = 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)

显然答案是“否”。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM