python最简单的方法将字典插入数据库表中?

发布于 2025-02-05 05:46:37 字数 631 浏览 3 评论 0 原文

我有一个词典带有键和值,例如:

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操作,但这似乎效率低下。

  1. 使用循环插入值的最简单方法是什么?
  2. 我该如何编写它,以便将一个值插入所有值?

I have a dictionary with keys and values like:

my_dict = {'a':33, 'b': 'something', 'c': GETDATE(), 'd': 55}

Assume column names in the SQL table are also named like the keys of the dict, i.e. "a,b,c,d".

The actual dictionary is 20+ key:value pairs.

Code

I have used pyodbc.connect to create a cursor which I could use to execute an SQL INSERT statement:

for k in my_dict.keys():
    cursor.execute(
    '''
        INSERT INTO TABLEabc (%s)
        VALUES (%s)
    '''
    % (k, my_dict[k])
    )

This seems inefficient though because it's a new SQL operation each time.

  1. What is the easiest way to insert the values using a loop?
  2. How could I write it so that it just makes one insert with all the values?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

秋日私语 2025-02-12 05:46:38

补充 jontout的答案,如果您使用sqlalchemy,那么您的dict就可以被Sqlalchemy Core 对象:

import datetime

import sqlalchemy as sa

connection_url = sa.engine.URL.create("mssql+pyodbc", … )
engine = sa.create_engine(connection_url)

table_abc = sa.Table("TABLEabc", sa.MetaData(), autoload_with=engine)

my_dict = {'a':33, 'b': 'something', 'c': datetime.date.today(), 'd': 55}

with engine.begin() as conn:
    conn.execute(table_abc.insert(), my_dict)

Supplemental to JonTout's answer, if you use SQLAlchemy then your dict is ready-made to be consumed by a SQLAlchemy Core Table object:

import datetime

import sqlalchemy as sa

connection_url = sa.engine.URL.create("mssql+pyodbc", … )
engine = sa.create_engine(connection_url)

table_abc = sa.Table("TABLEabc", sa.MetaData(), autoload_with=engine)

my_dict = {'a':33, 'b': 'something', 'c': datetime.date.today(), 'd': 55}

with engine.begin() as conn:
    conn.execute(table_abc.insert(), my_dict)
酒浓于脸红 2025-02-12 05:46:37

如果您使用的是pyodbc,则可能会起作用:

columns = {row.column_name for row in cursor.columns(table='TABLEabc')}

safe_dict = {key: val for key, val in my_dict.items() if key in columns}

# generate a parameterised query for the keys in our dict
query = "INSERT INTO TABLEabc ({columns}) VALUES ({value_placeholders})".format(
    columns=", ".join(safe_dict.keys()),
    value_placeholders=", ".join(["?"] * len(safe_dict)),
)

cursor.execute(query, list(safe_dict.values()))

它是为了免受SQL注入的安全性,因为:

  • 仅使用DB中实际列名的键
  • ,我们使用pyodbc光标执行参数,因此值将正确逃脱

我们 它可能无法正常工作:

  • 如果需要引用和逃脱的任何列名,则不会自动发生这种情况,因此它将失败

/逃脱是DB特定的,因此我们必须检查我们实际DB的规则将其应用于我们格式化的dict键中的查询。 (或找到某种方法让PYODBC为我们做到这一点,如果可能的话,不确定)

如果您信任 my_dict 不包含恶意代码,则可以简化以下:

query = "INSERT INTO TABLEabc ({columns}) VALUES ({value_placeholders})".format(
    columns=", ".join(my_dict.keys()),
    value_placeholders=", ".join(["?"] * len(my_dict)),
)

cursor.execute(query, list(my_dict.values()))

If you're using pyodbc then this might work:

columns = {row.column_name for row in cursor.columns(table='TABLEabc')}

safe_dict = {key: val for key, val in my_dict.items() if key in columns}

# generate a parameterised query for the keys in our dict
query = "INSERT INTO TABLEabc ({columns}) VALUES ({value_placeholders})".format(
    columns=", ".join(safe_dict.keys()),
    value_placeholders=", ".join(["?"] * len(safe_dict)),
)

cursor.execute(query, list(safe_dict.values()))

It is intended to be safe from SQL injection because:

  • we filter for only keys which are actual column names in the db
  • we use pyodbc cursor execute params, so the values will be escaped properly

Where it possibly won't work:

  • if any of the column names need to be quoted and escaped, this won't happen automatically so it will fail

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:

query = "INSERT INTO TABLEabc ({columns}) VALUES ({value_placeholders})".format(
    columns=", ".join(my_dict.keys()),
    value_placeholders=", ".join(["?"] * len(my_dict)),
)

cursor.execute(query, list(my_dict.values()))
相守太难 2025-02-12 05:46:37

使用SQLalchemy,该字典在SQL Server中与我的表构造匹配

mydict = {
  "Name": "Laura", "Form": "4B","Year": "7", "DOB" : "", "Col_5" : "",
  "Col_6" : "","Col_7" : "","Col_8" : ""  
}

print(mydict)

,我用它将键和值传递给字符串(带有某些操纵)的表格,这称为pypupil)
我还想为所有记录编写数据,无论是否存在字典中。

fields = (str(list(mydict.keys()))[1:-1])
values = (str(list(mydict.values()))[1:-1])

columns = ', '.join("`" + str(x).replace('/', '_') + "`" for x in mydict.keys())
values = ', '.join("'" + str(x).replace('/', '_') + "'" for x in mydict.values())
sql = "INSERT INTO %s ( %s ) VALUES ( %s );" % ('pypupil', columns, values)

sql = sql.replace ( "`","") 
print(sql)

with engine.connect() as con:
    rs = con.execute(sql)

此处有更多信息和许多帮助者。

Using SQLAlchemy, this dictionary matches my table construct in SQL Server

mydict = {
  "Name": "Laura", "Form": "4B","Year": "7", "DOB" : "", "Col_5" : "",
  "Col_6" : "","Col_7" : "","Col_8" : ""  
}

print(mydict)

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.

fields = (str(list(mydict.keys()))[1:-1])
values = (str(list(mydict.values()))[1:-1])

columns = ', '.join("`" + str(x).replace('/', '_') + "`" for x in mydict.keys())
values = ', '.join("'" + str(x).replace('/', '_') + "'" for x in mydict.values())
sql = "INSERT INTO %s ( %s ) VALUES ( %s );" % ('pypupil', columns, values)

sql = sql.replace ( "`","") 
print(sql)

with engine.connect() as con:
    rs = con.execute(sql)

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/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文