我有一个文本文件,其中有一行单词,例如:
One Two Three
Four Five Six
我需要在数据库的单独列中获取每个“单词”。
到目前为止,我想到了以下代码:
connection = sqlite3.connect("test.db")
cursor = connection.cursor()
sql_command = """CREATE TABLE IF NOT EXISTS test (
id VARCHAR(20),
second VARCHAR(20),
third VARCHAR(20),
fourth VARCHAR(20));"""
cursor.execute(sql_command)
query = "INSERT INTO test VALUES (NULL,?,?,?)"
filename = open("test.txt", "r")
with open("test.txt", "r") as filename:
for data in filename:
line = data.split()
print(line)
cursor.execute(query, data.split(' '))
connection.commit()
connection.close()
我收到以下错误消息:
Incorrect number of bindings supplied. The current statement uses 3, and there are 1 supplied.
如果我将代码更改为:
query = "INSERT INTO test VALUES (NULL,?,NULL,NULL)"
整行都写入数据库:
1|One Two Three||
2|Four Five Six||
参考方案
我必须编写以下内容进行测试和数据生成:
import sqlite3, os
with open("test.txt", "w") as txt:
for i in range(10):
txt.write("One Two Three\n")
if not os.path.exists("test.db"):
connection = sqlite3.connect("test.db")
else:
os.remove("test.db")
connection = sqlite3.connect("test.db")
您没有遍历文本文件中的各行。很好:
cursor = connection.cursor()
sql_command = """CREATE TABLE IF NOT EXISTS test (
id VARCHAR(20),
second VARCHAR(20),
third VARCHAR(20),
fourth VARCHAR(20));"""
cursor.execute(sql_command)
query = "INSERT INTO test VALUES (NULL,?,?,?)"
但是对于读/写,您需要进行如下更改以遍历各行:
with open("test.txt", "r") as filename:
for data in filename:
line = data.split()
print(line)
if len(line) == 3:
cursor.execute(query, data.split())
connection.commit()
connection.close()
Python uuid4,如何限制唯一字符的长度 - python在Python中,我正在使用uuid4()方法创建唯一的字符集。但是我找不到将其限制为10或8个字符的方法。有什么办法吗?uuid4()ffc69c1b-9d87-4c19-8dac-c09ca857e3fc谢谢。 参考方案 尝试:x = uuid4() str(x)[:8] 输出:"ffc69c1b" Is there a way to…
Python-crontab模块 - python我正在尝试在Linux OS(CentOS 7)上使用Python-crontab模块我的配置文件如下:{ "ossConfigurationData": { "work1": [ { "cronInterval": "0 0 0 1 1 ?", "attribute&…
Python:检查是否存在维基百科文章 - python我试图弄清楚如何检查Wikipedia文章是否存在。例如,https://en.wikipedia.org/wiki/Food 存在,但是https://en.wikipedia.org/wiki/Fod 不会,页面只是说:“维基百科没有此名称的文章。”谢谢! 参考方案 >>> import urllib >>> prin…
带有可变表和字段名称的web2py插入,例如与字典 - python有没有一种在运行时处理表名和字段名的方法?我发现了对将dict作为参数的插入方法的引用但是假设rd是一个包含10个条目的字典,key =字段名称,value =要插入的值,以下代码将失败 db.OrdersFull.insert(rd) 带有错误:TypeError:insert()恰好接受1个参数(给定2个)1)有什么线索吗?2)使用此解决方案,必须在开发…
Python Pandas导出数据 - python我正在使用python pandas处理一些数据。我已使用以下代码将数据导出到excel文件。writer = pd.ExcelWriter('Data.xlsx'); wrong_data.to_excel(writer,"Names which are wrong", index = False); writer.…