谢谢你的帮助。我是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: File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/encodings/ascii.py", line 26, in decode return codecs.ascii\_decode(input, self.errors)[0] UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)发布于 2014-12-29 01:39:01
你没有显示你得到的错误。
但是,您似乎混淆了sqlite3和MySQL。这是两个完全独立的数据库,但您的问题标题引用了"mysqlite3“。在代码中连接到sqlite db文件,然后尝试运行LOAD DATA,这是sqlite不支持的特定于MySQL的命令。
您必须编写一些Python代码来读取CSV文件、遍历并将每一行插入到数据库中。csv模块将会有所帮助。
发布于 2014-12-29 01:39:34
据我所知,sqlite不支持LOAD DATA LOCAL INFILE。
您应该逐行解析文件并生成插入,或者使用import命令
https://www.sqlite.org/cli.html
搜索.import
https://stackoverflow.com/questions/27678689
复制相似问题