Python and mySQLdb error: OperationalError: (1054, "Unknown column in 'where clause'")
Asked Answered
D

3

6

Hey all, I'm getting an error

OperationalError: (1054, "Unknown column 'XX' in 'where clause'")

Where XX is the value of CLASS in the following code

conn = MySQLdb.connect(host = "localhost",user = "user", passwd = "pass",db = "dbase")
cursor = conn.cursor()
cursor.execute("""SELECT * FROM %s WHERE course =%s AND sec = %s""" % (str(DEPT),str(CLASS),str(SEC),))

The thing is, I only get this error with certain values, namely, when CLASS contains a letter. I have the table set up as varchar if that helps

Thanks!

Diwan answered 11/8, 2010 at 20:49 Comment(0)
S
7

Don't use "string injection" into your SQL except for cases where it's truly indispensable, such as the str(DEPT) here to choose what table you're selecting from. For every other case, use the parameter passing feature of the Python DB API instead -- it will quote things properly for you and automatically defend you against "SQL injection" attacks, among other things. (It can also be faster, sometimes).

Since MySQLdb uses the unfortunate notation %s for parameters, here's what you should do (also fixing the style to be PEP8-compliant, not required but can't hurt;-):

conn = MySQLdb.connect(host="localhost", user="user", passwd="pass", db="dbase")
cursor = conn.cursor()
q = 'SELECT * FROM %s WHERE course=%%s AND sec = %%s""" % (DEPT,)
cursor.execute(q, (CLASS, SEC))

The %%s in the string formatting which produces q become a single % each upon formatting, so q is left with two occurrences of %s -- which the execute fills in neatly with correctly formatted versions of CLASS and SEC. All the str calls are redundant, etc.

As an aside, if you're on Python 2.6 or later, for string formatting you should use the new format method instead of the old % operator -- that saves you from the need for those "doubled up % signs", among other advantages. I haven't applied that change in the above snippet just in case you're stuck with 2.5 or earlier (so the code above works in any version of Python, instead of just in reasonably recent ones).

Sociability answered 11/8, 2010 at 21:0 Comment(2)
Sorry, but I'm really new to SQL and Python. Could you explain what parameter passing is if it not too big a deal? Thanks!Diwan
@Jill, sure, see the edit I just did to my answer -- I simply rewrote your code to make it correct (and PEP8-compliant as to where the spaces go or don't for elegant style, and more speedy and readable by avoiding a bunch of redundant str calls, but those are only side issues here;-).Sociability
D
1

Instead of:

course=%s

I think you need:

course='%s'
Dorcasdorcea answered 11/8, 2010 at 21:3 Comment(1)
Alex's answer is the better approach.Dorcasdorcea
D
0

I had same error, I just added a new field in my model and table ie. id field. and it's working properly.

Denney answered 11/6, 2018 at 5:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.