【问题标题】:Python and sqlite3 - import text file into databasePython 和 sqlite3 - 将文本文件导入数据库
【发布时间】:2014-12-28 17:12:19
【问题描述】:

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

【问题讨论】:

  • 您说您想将一个名为 names.txt 的文件加载到数据库中,但您确实加载了一个文件 addresses.txt... 抱歉提出了明显的问题,但有时... :-)
  • 对不起,我的错字。感谢您的发现 - 我希望就这么简单!

标签: python database sqlite


【解决方案1】:

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

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

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

【讨论】:

  • 附带说明,在读取 csv 并将字段构造成列表后更好,然后执行 executemany 批量插入。
  • 我尝试使用 csv 模块但收到错误。我已经编辑了最初的问题。感谢您迄今为止的帮助。
【解决方案2】:

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

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

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

搜索 .import

【讨论】:

  • 这是一个 Python 问题,参考 CLI 文档并没有太大帮助
猜你喜欢
  • 2011-02-22
  • 2011-06-10
  • 2019-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-11
  • 2015-02-05
相关资源
最近更新 更多