您好,感谢您点击此问题。我想将用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值时DB显示的消息。
更新
我尝试通过回答Forcing a data type (BLOB or TEXT) when inserting values into an SQLite table的另一个问题来实施解决方案。意思是我做了以下事情:
1)尝试根据解决方案编号1重写数据库中的值,但这并不能解决我的问题
2)其他文章的另一个建议是,我应该确保将文本值插入数据库。据我所知,我尝试插入数据库的值是字符串。为了确保我甚至将从文本文件中提取的描述强制为字符串。但是,这不能解决我的问题。
因此,我认为我的问题不是重复的,因为我将字符串插入与文本相似的列中并将其存储为二进制。如果对此我错了,请问有人可以更详细地解释到底发生了什么以及为什么我得到这个结果。我在其他数据库插入中使用了类似的代码,但从未收到这样的错误...
谢谢!
答案 0 :(得分:0)
感谢 https://stackoverflow.com/users/570339/ramy-al-zuhouri 和 sqlite 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)