2014-12-28 75 views
0

感謝您的幫助。我是SQLite3的新手,確實混淆了兩者。我已經嘗試了下面的代碼,但它仍然不起作用。Python和sqlite3 - 將文本文件導入數據庫

import csv 
import sqlite3 

# Create the database 
connection = sqlite3.connect('addresses.db') 
cursor = connection.cursor() 

# Create the table 
cursor.execute('DROP TABLE IF EXISTS addresses') 
cursor.execute('''CREATE TABLE addresses 
      (ID text, Firstname text, Surname text, Address1 text, Address2 text, Postcode text)''') 
connection.commit() 

# Load the CSV file into CSV reader 
csvfile = open('addresses.txt', 'r') 
creader = csv.reader(csvfile, delimiter=',', quotechar='"') 

# Iterate through the CSV reader, inserting values into the database 
for t in creader: 
    cursor.execute('INSERT INTO addresses VALUES (?,?,?,?,?,?)', t) 

# Close the csv file, commit changes, and close the connection 
csvfile.close() 
connection.commit() 
connection.close() 

我得到的錯誤
在creader T: 文件 「/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/encodings/ascii.py」,第26行,在解碼 返回codecs.ascii_decode(輸入,self.errors)[0] UnicodeDecodeError錯誤: 'ASCII' 編解碼器不能在位置0解碼字節0xe2:在範圍序數不(128)

+1

你說你要加載一個叫做'名字的文件。 txt'到數據庫中,但你實際上加載了一個文件'addresses.txt' ...對不起,提出明顯的,但有時... :-) – zmo

+0

對不起,我的錯字。感謝您的發現 - 我希望這很簡單! – g3561

回答

2

您沒有顯示出你得到的錯誤。

但是,似乎你在sqlite3和MySQL之間感到困惑。這是兩個完全獨立的數據庫,但您的問題標題引用了「mysqlite3」。你連接到你的代碼中的sqlite數據庫文件,但是然後你嘗試運行LOAD DATA,這是一個MySQL特有的命令,不受sqlite支持。

您將不得不編寫一些Python代碼來讀取CSV文件,迭代並將每行插入數據庫。 csv模塊將有所幫助。

+0

作爲一個附註,在閱讀csv並將字段構造成列表之後更好,然後執行'executemany'來批量插入。 – Anzel

+0

我試圖使用csv模塊,但收到錯誤。我編輯了最初的問題。感謝您一直以來的幫助。 – g3561