首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python和sqlite3 -将文本文件导入数据库

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

Stack Overflow用户
提问于 2014-12-29 01:12:19
回答 2查看 4.3K关注 0票数 1

谢谢你的帮助。我是SQLite3的新手,我确实把两者搞混了。我已经尝试了下面的代码,但它仍然不能工作。

代码语言:javascript
复制
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()

我得到了错误

代码语言:javascript
复制
 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)
EN

回答 2

Stack Overflow用户

发布于 2014-12-29 01:39:01

你没有显示你得到的错误。

但是,您似乎混淆了sqlite3和MySQL。这是两个完全独立的数据库,但您的问题标题引用了"mysqlite3“。在代码中连接到sqlite db文件,然后尝试运行LOAD DATA,这是sqlite不支持的特定于MySQL的命令。

您必须编写一些Python代码来读取CSV文件、遍历并将每一行插入到数据库中。csv模块将会有所帮助。

票数 2
EN

Stack Overflow用户

发布于 2014-12-29 01:39:34

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

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

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

搜索.import

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27678689

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档