2017-05-24 90 views
1

我已經搜索了很多例子,但沒有一個能夠解決我的具體問題。感謝您抽出時間,因爲我無法爲我的生活尋找解決辦法。我試圖在Python中使用for循環將CSV文件插入到Azure SQL Server數據庫中。我已經使用這個相同的Python程序無數次將多個不同的CSV文件,所以我知道底層的問題是這個當前的CSV。以下是我的Python代碼的簡短片段,以及錯誤。我怎樣才能編碼的CSV,所以這個錯誤不再發生(如上所述,我嘗試了來自多個類似的線程的解決方案,並沒有能夠解決這個問題)。'ascii'編解碼器無法解碼 - 通過pyodbc CSV到SQL Server

代碼:

csvfile = open('C:\\file.csv', 'r') 
    csv_data = csv.reader(csvfile) 

    SQL = """Insert into Idea_Pipeline([col_1], [col_2], [col_3], [col_4]) 
      values (?,?,?,?) 

    for row in csv_data: 
    first_row = next(csv_data) 
    cursor2.execute(SQL, row) 

如前所述,這只是我的代碼片段,但我已經使用這個無數次,所以我知道的語法是正確的。以下是我無法解決的錯誤。

錯誤:

Traceback (most recent call last): 
File "Idea_Pipeline.py", line 46, in <module> 
cursor2.execute(SQL, row) 
UnicodeDecodeError: 'ascii' codec can't decode byte 0x96 in position 114: 
ordinal not in range(128) 

再次,非常感謝你的所有幫助。

而且 - 我又

感謝試圖批量插入這個CSV到本地SQL Server數據庫,並已收到錯誤「操作系統錯誤代碼(空)」的任何幫助或建議,因爲我還是有點新的和我試圖儘可能多地學習可以。

回答

2

聽起來這是您的CSV文件第一次包含'ascii'編解碼器無法處理的字符。 0x96不是latin1字符集中的字符之一,因此下一個最有可能的候選字符可能是windows-1252,其中0x96表示「En Dash」字符(U + 2013)。如果是這樣的話,那麼

# -*- coding: windows-1252 -*- 
import csv 
import pyodbc 
import sys 
print("Python version " + sys.version) 
print("pyodbc version " + pyodbc.version) 
cnxn = pyodbc.connect("DSN=myDb", autocommit=True) 
crsr = cnxn.cursor() 
crsr.execute("CREATE TABLE #foo (id INT PRIMARY KEY, txtcol VARCHAR(50))") 

with open(r'C:\Users\gord\Desktop\sample.csv', 'rb') as csvfile: 
    csv_data = csv.reader(csvfile) 
    sql = "Insert into #foo ([id], [txtcol]) VALUES (?,?)" 
    print("") 
    print("Rows retrieved from CSV file:") 
    for row in csv_data: 
     print(row) 
     crsr.execute(sql, [cell.decode('windows-1252') for cell in row]) 
print("") 
print("Values retrieved from table:") 
for row in crsr.execute("SELECT * FROM #foo").fetchall(): 
    print(row) 
cnxn.close() 

將產生如下輸出

Python version 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] 
pyodbc version 4.0.16 

Rows retrieved from CSV file: 
['1', 'foo'] 
['2', 'test\x96data'] 

Values retrieved from table: 
(1, u'foo') 
(2, u'test\u2013data') 
相關問題