我试图插入一个utf-8字符串,但我得到了:
sqlite3.ProgrammingError:除非使用可解释8位字节串的text_factory(如text_factory = str),否则不得使用8位字节串。强烈建议您只需将应用程序切换为Unicode字符串。
Here is the whole module。以下是代码的相关部分:
########### reading json from a utf-8 file:
with open(file_name) as f:
return json.loads(f.read())
########### feeding utf-8 encoded text to constructor
for obveznik in json:
vlasnici[obveznik["id_obveznik"]] = Vlasnik(obveznik["id_obveznik"], obveznik["naziv"].encode('utf-8'))
########### constructor simply assigns
class Vlasnik
def __init__(self, id, ime):
self._id = id
self._ime = ime
########### here's a getter in the same class:
def ime(self):
return self._ime
########### and then I use the getter
cur.execute("INSERT INTO indeksi VALUES(?, ?, ?, ?, ?, ?)", (
# [...]
vlasnik.ime(),
# [...]
))
########################
我在cur.execute()上得到了sqlite3.ProgrammingError。我读取字符串frmo utf-8文件并使用.encode(' utf-8')将其分配给类字段。我还需要做什么? : - /
提前致谢。
答案 0 :(得分:1)
如果您的字符串已经是UTF-8,那么请不要使用encode
,只需传递它而不进行处理。如果没有,请使用.decode("utf-8")
。
使用Python 2.x时,请考虑始终使用unicode字符串。当它涉及文件IO时,请考虑使用io
模块而不是内置的open
函数,它可以指示特定的enconding。
import io
f = open("file.txt", enconding="utf-8")
希望它有所帮助。