简体   繁体   中英

python sqlite3 syntax error with string when doing update

I have this function in python that attempts to update the table with a string:

table.execute("UPDATE " + tableName + " SET " +
                       colName + "=" + colVal +
                        " WHERE " + name + "=(" + val + ")")

It always return the error: sqlite3.OperationalError: near "Look": syntax error.

How should I process my "val" value so that the string can be added into the database?

==update== tried this query and it didn't work either:

table.execute("UPDATE " + tableName + " SET " +
                        colName + "=" + colValue +
                        " WHERE " + name + "= ?", (val,))

There are major flaws in using direct variables in sql queries:

http://www.w3schools.com/sql/sql_injection.asp

Read up more on them. But if you do want to make your code work you can do the following change:

table.execute("UPDATE " + tableName + " SET " +
                       colName + "='" + colVal + 
                        "' WHERE " + name + "=('" + val + "')")
table.commit()

Since val/colVal are strings being passed to the query so it should be escaped.

Have added sample example here which works: https://gist.github.com/vi3k6i5/869d299e8afe99593b79ae41051ebf63

As @Deepspace pointed out in the comment, SQL directly executed on db is not safe.

Hence a good way to do all this is to use an ORM. Something like django or SQLalchemy

Go through their examples they are pretty simple. And they have their own structure to make changes to db. Update/Insert/Delete everything.

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