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

标签 python database sqlite

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

相关文章:

SQL Server 根据不同表中的另一列更新新列

android - 在 Android 中通过 SQLite 保存数据时 COLUMN_NAME_NULLABLE 的必要性?

python - 使用 scrapy 进行 CPU 密集型解析

python - 如何使用 Twitter 搜索 API 获取所有带有给定主题标签的推文?

java - 房间架构导出目录 - 找不到参数的方法 javaCompileOptions()

database - 关于数据库索引的问题

ios - 为什么 sqlite 插件不能与 ios 上的 cordova 应用程序一起使用

sql - 如何检查字符串是否包含 case 语句中的单词 - SQLite

python - 在 Python 中访问数组列的最佳方法是什么?

python - 检查列表并相应地编辑第二个列表