Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/eclipse/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用pyodbc将列表插入odbc行的优雅方式_Python_Sql Server_Tsql_Python 2.7_Pyodbc - Fatal编程技术网

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

Python 使用pyodbc将列表插入odbc行的优雅方式,python,sql-server,tsql,python-2.7,pyodbc,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,

我刚刚开始学习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()
这里我得到一个错误:

编程错误:(“参数类型无效。参数索引=4” 参数类型=列表,“HY105”)

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


谢谢

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

  • 确定insert语句所需的参数占位符数
  • 从单个变量(
    key
    thisDate
    )和字典值构建参数值序列

  • 上述代码尚未测试。

    目标表定义是什么?@BryanEargle我已用表定义更新了OP
    ...
    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()