【问题标题】:Elegant way to insert list into odbc row using pyodbc使用 pyodbc 将列表插入 odbc 行的优雅方法
【发布时间】:2014-12-29 03:30:21
【问题描述】:

我刚刚进入 python 和 SQL。我能够连接到我的数据库,并从中查询。现在我想插入行。特别是,我有一本列表字典。我想将每个列表作为一行的一部分插入到数据库中。由于我的列表很长,我想找到一种优雅的方式来完成它。

表格由定义给出:

CREATE TABLE [dbo].[ExampleTable](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Date] [date] NOT NULL,
    [Name] [nvarchar](50) NOT NULL,
    [columnA] [nvarchar](50) NULL,
    [columnB] [int] NOT NULL,
    [columnC] [decimal](5, 4) NOT NULL,
    [columnD] [int] NOT NULL
    ...
    [columnX] [nvarchar](50) NOT NULL
)

到目前为止我有:

import pyodbc
import datetime
import time

cnxn = pyodbc.connect(connStr)
db_cursor = cnxn.cursor()

myDict = dict()
myDict['key1'] = ['John Doe', 5, 0.978, -1, ..., 'x'] # there are many columns here
thisDate =  datetime.date(2014, 10, 22)
myTable = ExampleTable

insertQuery  = "insert into %s value(?, ?, ?)" %myTable


for key in myDict:
    db_cursor.execute(insertQuery, key, thisDate.strftime('%Y-%m-%d'), myDict[key])
    cnxn.commit()

这里出现错误:

ProgrammingError: ('无效的参数类型。param-index=4 param-type=list', 'HY105')

有没有办法优雅地做到这一点,而不必引用字典列表中的每个元素?

谢谢!

【问题讨论】:

  • 目标表定义是什么?
  • @BryanEargle 我已经用表定义更新了 OP

标签: python sql-server tsql python-2.7 pyodbc


【解决方案1】:

由于您似乎正在尝试使插入表不可知,因此您至少需要:

  1. 确定插入语句所需的参数占位符? 的数量
  2. 根据单个变量(key 和 thisDate)和字典值构建一系列参数值
...
myDict = dict()
myDict['key1'] = ['John Doe', 5, 0.978, -1, ..., 'x'] # there are many columns here
thisDate =  datetime.date(2014, 10, 22)

# get number of columns from target table to determine number of placeholders
# for insert, change schema as needed
columns = db_cursor.columns(table=mytable, schema='dbo').fetchall()

# build DML with dynamic table name and placeholders
insertQuery  = "insert into {0} values ({1})".format(myTable, ','.join('?' * len(columns))

for key in myDict:
    # build parameter list from individual variable and dictionary values
    params = [key, thisDate] + myDict[key]
    db_cursor.execute(insertQuery, params)
    cnxn.commit()

以上代码未经测试。

【讨论】:

  • 小错字。行尾缺少右括号 ...len(columns)) 应为 ..len(columns)))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-07
  • 2015-04-08
  • 1970-01-01
  • 2020-09-04
  • 2010-10-03
  • 2019-09-18
相关资源
最近更新 更多