Python and mySQLdb error: OperationalError: (1054, Unknown column in where clause)

2024/11/10 13:40:43

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!

Answer

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

https://en.xdnf.cn/q/72504.html

Related Q&A

Best Python GIS library? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, argum…

Build a class with an attribute in one line

How do I write a one-liner for the following? class MyClass(): content = {} obj = MyClass()

Python Imports, Paths, Directories Modules

Let me start by saying Ive done extensive research over the course of the past week and have not yet found actual answers to these questions - just some fuzzy answers that dont really explain what is g…

Finding location in code for numpy RuntimeWarning

I am getting warnings like these when running numpy on reasonably large pipeline. RuntimeWarning: invalid value encountered in true_divideRuntimeWarning: invalid value encountered in greaterHow do I fi…

Django, Angular, DRF: Authentication to Django backend vs. API

Im building an app with a Django backend, Angular frontend, and a REST API using Django REST Framework for Angular to consume. When I was still working out backend stuff with a vanilla frontend, I used…

Django view testing

Im trying to figure out if there is a quick way to test my django view functions form either the python or django shell. How would I go about instantiating and passing in faux HTTPrequest object?

Remove non-ASCII characters from string columns in pandas

I have panda dataframe with multiple columns which mixed with values and unwanted characters. columnA columnB columnC ColumnD \x00A\X00B NULL \x00C\x00D 123 \x00E\X00F…

Open source Twitter clone (in Ruby/Python) [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.We don’t allow questi…

What is the best way to connect to a Sybase database from Python?

I am trying to retrieve data in a Sybase data base from Python and I was wondering which would be the best way to do it. I found this module but may be you have some other suggestions: http://python-sy…

How to get N random integer numbers whose sum is equal to M

I want to make a list of N random INTEGER numbers whose sum is equal to M number.I have used numpy and dirichlet function in Python, but this generate double random number array, I would like to genera…