i'm practicing on Python and trying to create a class that helps performing database operations, but when inserting to a database here's the code :
def Insert(self, **kwargs):
self.__query.execute("INSERT INTO {} ({}) VALUES ({})".format(self.table, ", ".join(kwargs.keys()), ", ".join(str(v) for v in kwargs.values())))
self.__db.commit()
When i ran this code for testing:
MyTable.Insert(id=3, name="jack", age=23)
I got this error :
sqlite3.OperationalError: no such column: jack
When i replaced the execute
command with print
i got this :
INSERT INTO testTbl111 (id, name, age) VALUES (3, jack, 23)
I guess jack
must be surrounded by quotations.
My question: is how to surround jack
with quotation while doing ", ".join(str(v) for v in kwargs.values())
?
You don't want to try to escape value parameters yourself, instead you want to build the insert
query and put placeholders ( ?
works for sqlite3) for values
- something like:
query = 'INSERT INTO {} ({}) VALUES({})'.format(self.table, ', '.join(kwargs), ','.join(['?'] * len(kwargs)))
Then, use the second method of execute (either on the db object or cursor object) to pass in the values to be substituted - these will automatically be correctly escaped for the database.
self.__db.execute(query, list(kwargs.values()))
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.