简体   繁体   中英

SQL Code not executing properly

So I have this piece of code:

sql1 = "SELECT * FROM CustomerTable WHERE " + variable.get() + " = " + Queryby.get()
print(sql1)

and when I run this code, the print outputs this:

SELECT * FROM CustomerTable WHERE Title = Mr

which suggests that the code should work when it is executed. However, when I change the print(sql1) to cursor.execute(sql1) , it outputs the following error message:

sqlite3.OperationalError: no such column: Mr

This is really confusing for me because of where the Mr is would suggest it is what is being searched for, not what the column is called. Any suggestions?

You need to wrap Mr with a single apostrophe like so 'Mr' . That way, SQL recognizes it as a string and not a column.

Basically, your line should be this:

sql1 = "SELECT * FROM CustomerTable WHERE " + variable.get() + " = '" + Queryby.get() + "'"

You may also format it differently if you wish to avoid all the plus signs like so:

sql1 = "SELECT * FROM CustomerTable WHERE {} = '{}'".format(variable.get(), Queryby.get())

Keep in mind formatting the string yourself might result in SQL injection attacks if the input is given from the outside. See the documentation regarding formatting with ? .

Constructing your query dynamically like this opens you to injection attacks when finally executed. Instead, use a parameterized query:

# This is a little extreme...
sql1 = "SELECT * FROM CustomerTable WHERE ? = ?"
cursor.execute(sql1, (variable.get(), Queryby.get()))

This relieves you of the job of making sure the dynamic elements are properly quoted.

Add quotes around "Mr". Like:

sql1 = "SELECT * FROM CustomerTable WHERE " + variable.get() + " = '" + Queryby.get() + "'"

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