感谢您的帮助。我是 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()
我得到了错误
对于创建者中的 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)
最佳答案
您没有显示您遇到的错误。
但是,您似乎对 sqlite3 和 MySQL 感到困惑。这是两个完全独立的数据库,但您的问题标题是指“mysqlite3”。您在代码中连接到一个 sqlite 数据库文件,但随后您尝试运行 LOAD DATA,这是 sqlite 不支持的特定于 MySQL 的命令。
您将必须编写一些 Python 代码来读取 CSV 文件、遍历并将每一行插入数据库。 csv
模块会有所帮助。
关于Python 和 sqlite3 - 将文本文件导入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27678689/