尝试插入CSV文件时出现PyODBC语法错误

时间:2020-09-25 13:38:25

标签: sql sql-server pyodbc

for fileName in fileNames:
   with open(fileName, mode="rt", encoding="utf-8", newline="") as csvfile:
        csvFile = csv.reader(csvfile, delimiter=',')
        header = next(csvFile)
        headers = map((lambda x: x.strip()), header)
        insert = 'INSERT INTO TEST ('.format(tableChoice) + ', '.join(headers) + ') VALUES '
        for row , record in enumerate(csvFile, start=1):
            values = map((lambda x: "'"+x.strip()+"'"), record)

            myCursor.execute(insert +'('+ ', '.join(values) +');' )
            cnxn.commit()

到达脚本中的execute行时,出现以下错误。我只需要将从csv中提取的数据逐行插入数据库。有人知道导致错误的原因吗?

ProgrammingError :(“ 42000”,“ [42000] [Microsoft] [ODBC SQL Server驱动程序] [SQL Server]'-'附近的语法不正确。(102)(SQLExecDirectW)“)

编辑:

SQL查询字符串如下:

INSERT INTO TEST (this, that, those) VALUES ('1', '11', '111');
INSERT INTO TEST (this, that, those) VALUES ('2', '22', '222');
INSERT INTO TEST (this, that, those) VALUES ('3', '33', '333');

1 个答案:

答案 0 :(得分:1)

类似的问题是由于列名中的特殊字符引起的,例如-,这需要用方括号括起来才能在SQL Server中转义。另外,考虑使用一致的Python字符串格式和csv.DictReader来建立参数化查询,然后插入executemany进行插入:

for fileName in fileNames:
   with open(fileName, mode="rt", encoding="utf-8", newline="") as csvfile:
       reader = csv.DictReader(f)
       data = [row for row in reader]

       # BUILD SQL WITH [...] ESCAPED COLUMNS AND ? PARAM PLACEHOLDERS
       sql = "INSERT INTO [Test] ([{cols}]) VALUES ({prms})"
       sql = sql.format(cols="], [".join(map(lambda x: x.strip(), data[0].keys())), 
                        prms=", ".join(['?'] * len(data[0])))    
 
       # APPEND ALL ROWS AND BIND PARAMS
       myCursor.executemany(sql, [list(d.values()) for d in data])
       cnxn.commit()