Python和sqlite3 - 将文本文件导入数据库

时间:2014-12-28 17:12:19

标签: python database sqlite

感谢您的帮助。我是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()

我收到错误
    for t in creader:   文件" /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/encodings/ascii.py" ;,第26行,解码     return codecs.ascii_decode(input,self.errors)[0] UnicodeDecodeError:' ascii'编解码器不能解码位置0中的字节0xe2:序数不在范围内(128)

2 个答案:

答案 0 :(得分:2)

您没有显示您遇到的错误。

然而,似乎你在sqlite3和MySQL之间感到困惑。这是两个完全独立的数据库,但你的问题标题是指" mysqlite3"。您连接到代码中的sqlite db文件,但之后您尝试运行LOAD DATA,这是sqlite不支持的特定于MySQL的命令。

您必须编写一些Python代码来读取CSV文件,迭代并将每行插入数据库。 csv模块将提供帮助。

答案 1 :(得分:-1)

据我所知,sqlite不支持LOAD DATA LOCAL INFILE。

您应该逐行解析文件并生成插入 或使用导入命令

https://www.sqlite.org/cli.html

搜索.import