(' HY000',' SQL包含21个参数标记,但提供了1个参数')

时间:2017-03-01 22:56:34

标签: python sql-server python-3.x csv pypyodbc

我试图读取csv文件并在SQL中上传。这是代码。我收到此错误" pypyodbc.ProgrammingError:(' HY000',' SQL包含21个参数标记,但提供了1个参数')"我的csv文件有21列。你知道如何解决这个问题吗?

import csv
import pypyodbc
import traceback
import sys
import time
import os.path
import codecs


# Create a connection to DataBase
con = pypyodbc.connect('DRIVER={SQL Server};SERVER=c1devsql01.XXXXXX.com;DATABASE=Parameters;UID=XXXXXX;PWD=XXXX@1')

cur = con.cursor()
query = "insert into Calc_Rules_Metadata_New (Calc_Set, Calc_Set_Identifier, Dependency, Data_Subset_Keys, Calc_Step, Calc_Variable, Calc_Operator, Calc_Operand, By_Variable, Where_Clause, Source_Tracking_Columns, Source_Tracking_Rows, Revision, Tag, Notes, Updated_By, Updated_On, IsDeleted, Metadata_Type, Calculation_Summary) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"

filename = str(sys.argv[1]) 
basedir = 'C:/RiskClient/InputData/Metadata/Calc'
fullpath = os.path.join(basedir, filename)

with open(fullpath, 'r') as csvfile:
    next(csvfile) # Skip Header 
    reader = csv.reader(csvfile, delimiter=',')
    for row in reader:
        #for i in range(len(row)):
            #if row[i] == '':
            #    row[i] = None
        print(row)    
        cur.execute(query, row)   
    cur.commit()

运行时错误:

['1', '1', '1b.B: Question Test 1', '', 'PFA_Unique_Identifier, Fund_Unique_Identifier; Business_Date', '1', 'Total_Borrowing', 'SUM', 'Borrowings_Data.Amount', '', "UPPER(Borrowings_Data.Commitment_Type) IN ('COMMITTED_AND_DRAWN', 'UNCOMMITTED') AND Borrowings_Data.Business_Date = &Rep_Date AND Fund_Unique_Identifier In (select Fund_Unique_Identifier from Fund_Level_Information where Applicable_PF_Sections IS NOT NULL AND PFA_Unique_Identifier = &PFA_UID AND Business_Date = &Rep_Date)", '', '', '', '', '', '', '', '', 'Test Form', '']
Traceback (most recent call last):
  File "C:\RiskClient\InputData\Metadata\Calc\CalcMetadata.py", line 47, in <module>
    cur.execute(query, row)
  File "C:\Program Files\Python3.5.2\lib\site-packages\pypyodbc-1.3.3-py3.5.egg\pypyodbc.py", line 1470, in execute
  File "C:\Program Files\Python3.5.2\lib\site-packages\pypyodbc-1.3.3-py3.5.egg\pypyodbc.py", line 1263, in _BindParams
pypyodbc.ProgrammingError: ('HY000', 'The SQL contains 20 parameter markers, but 21 parameters were supplied')

2 个答案:

答案 0 :(得分:0)

您提供单个列表而不是完整的位置参数集。如果您在查询字符串中提供了那些?,而只是在row中提供了cur.execute(query, row),那么您有效地说要将该列表填入第一个?并避开& #39; t为剩下的二十个提供了任何参数。要解决此问题,您需要提供*args,如下所示:

cur.execute(query, *row)

确保您的行(即此方案中的列表)实际上有21个项目。否则,您仍然会收到有关未提供正确数量参数的错误。

答案 1 :(得分:0)

谢谢大家。我自己解决了这个问题。基本上运行时错误(&#39; HY000&#39;,&#39; SQL包含21个参数标记,但提供了1个参数&#39;)当csv列计数与插入查询参数不同时出现。在这种情况下,我的cvs文件有一个标识列&#34; Id&#34;因为这个库存假设是由SQL Server生成并自动增加的,因此映射不应该在csv文件中。从csv文件中删除该列可以解决该问题。感谢。