Python从文本文件中获取单词并写入sqlite3 db

时间:2019-02-28 13:57:35

标签: python sqlite

我有一个文本文件,其中有一行单词,例如:

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||

2 个答案:

答案 0 :(得分:0)

为了测试和数据生成,我必须编写以下内容:

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()

答案 1 :(得分:0)

好的,我找到了解决方法。

tgikal是正确的。抱歉,我没有看到您的评论。

        with open("test.txt", "r") as filename:
        for data in filename:
            line = data.split()
            print(line)
            cursor.execute(query, line)

谢谢大家的帮助。