How to surround only string with quotations when joining dictionary values using Python? -


i'm practicing on python , trying create class helps performing database operations, when inserting database here's code :

def insert(self, **kwargs):     self.__query.execute("insert {} ({}) values ({})".format(self.table, ", ".join(kwargs.keys()), ", ".join(str(v) v in kwargs.values())))     self.__db.commit() 

when ran code testing:

mytable.insert(id=3, name="jack", age=23) 

i got error :

sqlite3.operationalerror: no such column: jack

when replaced execute command print got :

insert testtbl111 (id, name, age) values (3, jack, 23) 

i guess jack must surrounded quotations.

my question: how surround jack quotation while doing ", ".join(str(v) v in kwargs.values()) ?

you don't want try escape value parameters yourself, instead want build insert query , put placeholders (? works sqlite3) values - like:

query = 'insert {} ({}) values({})'.format(self.table, ', '.join(kwargs), ','.join(['?'] * len(kwargs))) 

then, use second method of execute (either on db object or cursor object) pass in values substituted - these automatically correctly escaped database.

self.__db.execute(query, list(kwargs.values())) 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -