使用pyodbc将列表插入odbc行的优雅方式

时间:2014-12-29 03:30:21

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

我刚刚进入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')

有没有办法优雅地执行此操作,而无需引用字典列表中的每个元素?

谢谢!

1 个答案:

答案 0 :(得分:2)

因为看起来你正试图使插入表不可知,所以至少需要:

  1. 确定插入语句
  2. 所需的参数占位符数?
  3. 从单个变量(keythisDate)和字典值构建一系列参数值
  4. ...
    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()
    

    以上代码尚未经过测试。