【问题标题】:SqLite3: inserting text into text column gives binary data with PythonSqLite3:将文本插入文本列使用 Python 提供二进制数据
【发布时间】:2019-04-11 11:24:58
【问题描述】:

您好,感谢您点击此问题。我想将用 utf-8 编码的文本文件中的内容插入到数据库中。当继续将文本内容插入数据库时​​,它告诉我由于某种原因它是二进制数据。当我在 sqlite3 中创建数据库时,我已将描述(有问题的列)指定为 TEXT,因此我不知道可能是什么问题...

代码如下[它只包含我插入数据库的部分]: (代码的快速摘要:它正在查看一个包含许多文本文件的文件夹,然后它收集来自文本名称和内容的一些变量,然后如果文本尚未添加到数据库中,则添加一个新行,其中包含缺少与文本文件对应的变量)

def put_inside_db():
    counter = 0
    for item in list_txt:
        item_components = item.split("-")
        item_year = item_components[-1].split(".")
        unique_key = str(item_components[0]) + str(item_year[0])
        cik = item_components[0]
        comp_name = item_components[1]
        year = item_year[0]
        file_path = path_to_10k + item
        file = open(file_path, "r+", encoding="utf-8")
        description = file.read()
        description = str(description)
        print(description)
        file.close()
        if unique_key not in keys_db:
            c.execute("INSERT INTO finaldata (cik, comp_name, year, unique_key, description) "
                     "VALUES(?,?,?,?,?)", (cik, comp_name, year, unique_key, description))
            print("This key is not inside: " + unique_key)
            counter += 1
        else:
            "do nothing"
            # print("This key is inside: " + unique_key)
        if counter % 50 == 0:
            conn.commit()
    conn.commit()

我什至将文本文件的内部打印到控制台,它们是字符串,因此我不知道为什么会出现这个问题。您可以在下面看到当我单击“描述”列中的 a 值时数据库显示的消息

更新

我尝试从回答Forcing a data type (BLOB or TEXT) when inserting values into an SQLite table 的另一个问题中实施解决方案。意思是我做了以下事情:

1) 尝试通过根据解决方案一重写它们来修复数据库中的值,但这并没有解决我的问题

2) 另一篇文章的另一个建议是我应该确保将文本值插入到数据库中。据我所知,我尝试插入数据库的值是字符串。为了确保我什至强制从文本文件中提取的描述是一个字符串。但是,这并不能解决我的问题..

因此,在我看来,我认为我的问题不是重复的,因为我将字符串插入到与文本相关的列中,并将其存储为二进制。如果我对此有误,有人可以更详细地解释到底发生了什么以及为什么我会得到这个结果。我在其他数据库插入中使用过类似的代码,但从未收到过这样的错误...

谢谢!

【问题讨论】:

  • 请注意:您在 SQLite 中为列指定的类型只是它的亲和性。 SQLite 使用一种动态类型,因此您可以在任何列中存储任何类型的值,而不管其给定的亲和力如何。
  • 我不知道。知道这很有用:D 谢谢!
  • 我的问题类似于您提到的@stovfl,但我认为,我的问题有些不同,因为我确定我正在将文本插入到具有文本亲和力的列中,并且不知何故将其存储为二进制文件。我什至尝试将数据固定到列中:UPDATE finaldata SET description = CAST(description AS TEXT)
  • 您的description 中包含\n,这可能是原因。如果您可以确认这一点,请使用description = description.replace('<br>') 进行测试。

标签: python database string sqlite


【解决方案1】:

感谢 https://stackoverflow.com/users/570339/ramy-al-zuhourisqlite for swift is unstable

sqlite3_bind_int(statement, 1, Int32(id))
sqlite3_bind_text(statement, 2,(type as NSString).UTF8String, -1, nil)

let desc = (description ?? "") as NSString
sqlite3_bind_text(statement, 3, desc.UTF8String, -1, nil)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-03
    • 1970-01-01
    • 2012-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-19
    相关资源
    最近更新 更多