python最简单的方法将字典插入数据库表中?
我有一个词典带有键和值,例如:
my_dict = {'a':33, 'b': 'something', 'c': GETDATE(), 'd': 55}
在SQL表中的假设列名称也被命名为dict的键,即“ a,b,c,d”。
实际词典是20+密钥:值对。
代码
我已经使用了 pyodbc.connect 创建一个我可以可以的我可以创建 cursor
用于执行SQL插入语句:
for k in my_dict.keys():
cursor.execute(
'''
INSERT INTO TABLEabc (%s)
VALUES (%s)
'''
% (k, my_dict[k])
)
尽管这是每次新的SQL操作,但这似乎效率低下。
- 使用循环插入值的最简单方法是什么?
- 我该如何编写它,以便将一个值插入所有值?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
补充 jontout的答案,如果您使用sqlalchemy,那么您的dict就可以被Sqlalchemy Core
表
对象:
Supplemental to JonTout's answer, if you use SQLAlchemy then your dict is ready-made to be consumed by a SQLAlchemy Core
Table
object:如果您使用的是pyodbc,则可能会起作用:
它是为了免受SQL注入的安全性,因为:
我们 它可能无法正常工作:
/逃脱是DB特定的,因此我们必须检查我们实际DB的规则将其应用于我们格式化的dict键中的查询。 (或找到某种方法让PYODBC为我们做到这一点,如果可能的话,不确定)
如果您信任
my_dict
不包含恶意代码,则可以简化以下:If you're using pyodbc then this might work:
It is intended to be safe from SQL injection because:
Where it possibly won't work:
Quoting/escaping is db-specific so we would have to check the rules for our actual db and apply that to the dict keys that we format into the query. (or find some way to get pyodbc to do that for us, not sure if possible)
If you trust your
my_dict
not to contain malicious code then you can simplify to just:使用SQLalchemy,该字典在SQL Server中与我的表构造匹配
,我用它将键和值传递给字符串(带有某些操纵)的表格,这称为pypupil)
我还想为所有记录编写数据,无论是否存在字典中。
此处有更多信息和许多帮助者。
Using SQLAlchemy, this dictionary matches my table construct in SQL Server
and I use this to pass the keys and values to a string (with some manipulation) into my table, which is called pypupil)
I also wanted to write data for all records, whether present in the Dictionary or not.
A bit more info and lots of helpers for this approach here.
https://discuss.dizzycoding.com/using-a-python-dict-for-a-sql-insert-statement/