[英]How to surround only string with quotations when joining dictionary values using Python?
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 : 我正在使用Python进行练习,并试图创建一个有助于执行数据库操作的类,但是在插入数据库时,代码如下:
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 sqlite3.OperationalError:没有这样的列:jack
When i replaced the execute
command with print
i got this : 当我用print
替换execute
命令时,我得到了:
INSERT INTO testTbl111 (id, name, age) VALUES (3, jack, 23)
I guess jack
must be surrounded by quotations. 我猜jack
必须用引号引起来。
My question: is how to surround jack
with quotation while doing ", ".join(str(v) for v in kwargs.values())
? 我的问题:就是如何围绕jack
与报价,而做", ".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: 您不想自己尝试转义值参数,而是想要构建insert
查询并为values
放置占位符( ?
适用于sqlite3)-类似:
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. 然后,使用第二种执行方法(在db对象或游标对象上)传递要替换的值-这些值将自动为数据库正确转义。
self.__db.execute(query, list(kwargs.values()))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.