0

我正在尝试将整个 CSV 文件文件夹写入 SQL Server 表。我收到以下错误,我真的很难过:

Traceback (most recent call last):
  File "C:\\Projects\Import_CSV.py", line 37, in <module>
    cursor.execute("INSERT INTO HED_EMPLOYEE_DATA(Company, Contact, Email, Name, Address, City, CentralCities, EnterpriseZones, NEZ, CDBG)" "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", row)
DataError: ('22001', '[22001] [Microsoft][SQL Server Native Client 10.0][SQL Server]String or binary data would be truncated. (8152) (SQLExecDirectW); [01000] [Microsoft][SQL Server Native Client 10.0][SQL Server]The statement has been terminated. (3621)')

我不确定我的代码有什么问题。我还需要它跳过 CSV 文件中的第一行,因为那是标题行。任何帮助将不胜感激。谢谢你。

# Import arcpy module
import csv
import arcpy
import pyodbc as p
import os

# Database Connection Info
server = "myServer"
database = "myDB"
connStr = ('DRIVER={SQL Server Native Client 10.0};SERVER=' + server + ';DATABASE=' + database + ';' + 'Trusted_Connection=yes')

# Open connection to SQL Server Table
conn = p.connect(connStr)

# Get cursor
cursor = conn.cursor()

# Assign path to Excel files
folder_to_import = "\\\\Server\\HED_DATA_CSV"
l_files_to_import = os.listdir(folder_to_import)
for file_to_import in l_files_to_import:
     if file_to_import.endswith('.CSV'):
         csv_files = os.path.join(folder_to_import, file_to_import)
         csv_data = csv.reader(file(csv_files))
         for row in csv_data:
             cursor.execute("INSERT INTO HED_EMPLOYEE_DATA(Company, Contact, Email, Name, Address, City, CentralCities, EnterpriseZones, NEZ, CDBG)" "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", row)

cursor.close()

conn.commit()

conn.close()

print"Script has successfully run!"
4

1 回答 1

3

你可以这样跳过第一行:

csv_data.next() #throw away first row
for row in csv_data:
    if len(row) >= 10:
        cursor.execute("INSERT ..." ...)

此外,您应该在执行之前检查以确保row包含足够的元素:

if len(row) >= 10: #use first ten values in row, if there are at least ten
    cursor.execute("INSERT ...", row[:10])

您当前将您的插入语句列为彼此相邻的两个字符串。这具有将它们连接在一起而中间没有空间的效果。您可能需要在“VALUES”之前留一个空格。

于 2013-06-04T22:23:19.523 回答