1

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.

Jason Swett
  • 43,526
  • 67
  • 220
  • 351
  • http://www.python.org/dev/peps/pep-0249/ – Ignacio Vazquez-Abrams Mar 02 '11 at 19:23
  • Hmm, searching that page for "quote" or "escape/escaping" doesn't turn up anything useful. I also checked each of the cursor objects listed there and didn't see anything that seemed relevant. What am I supposed to be looking at? – Jason Swett Mar 02 '11 at 19:28
  • 2
    You're supposed to be looking at the fact that you should never be generating queries by hand. – Ignacio Vazquez-Abrams Mar 02 '11 at 19:32
  • 3
    Ugh. One of you people again. – Jason Swett Mar 02 '11 at 20:12
  • 1
    The keyword you want to search for is 'prepared statement' – markijbema Mar 02 '11 at 22:05
  • 1
    A prepared statement isn't what I want, though. I want the SQL. Doing something like this - `cursor.execute("SELECT FROM tablename WHERE fieldname = %s", [value])` - wouldn't get me where I want. I could conceivably put together a separate array with all my values and pass that as the second argument to `cursor.execute()`, but that would be so much more hassle than escaping `v` right where it is, plus I think the code would be harder to follow. – Jason Swett Mar 03 '11 at 21:38

2 Answers2

1

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)

Community
  • 1
  • 1
markijbema
  • 3,985
  • 20
  • 32
0

Apparently the answer is "no."

Jason Swett
  • 43,526
  • 67
  • 220
  • 351