[英]Python and sqlite3 - import text file into database
谢谢你的帮助。 我是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行,解码返回codecs.ascii_decode(input,self.errors)[ 0] UnicodeDecodeError:“ ascii”编解码器无法解码位置0的字节0xe2:序数不在范围内(128)
您没有显示得到的错误。
但是,您似乎在sqlite3和MySQL之间感到困惑。 这是两个完全独立的数据库,但您的问题标题是“ mysqlite3”。 您在代码中连接到sqlite db文件,但随后尝试运行LOAD DATA,这是sqlite不支持的MySQL特定命令。
您将必须编写一些Python代码来读取CSV文件,进行遍历并将每行插入数据库。 csv
模块会有所帮助。
据我所知,sqlite不支持LOAD DATA LOCAL INFILE。
您应该逐行解析文件并生成插入内容,或使用import命令
https://www.sqlite.org/cli.html
搜索.import
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.