【问题标题】:SQLite3 : You must not use 8-bit bytestrings unless you use a text_factorySQLite3:除非您使用 text_factory,否则不得使用 8 位字节串
【发布时间】:2015-08-25 20:03:51
【问题描述】:

为了自学python,一直在玩whois模块,还有sqlalchemy

我正在编写一个应用程序,它会遍历单词列表,并查找每个添加了 .tld 的单词。这运行良好,但某些数据返回使 SQLite 抛出以下错误

sqlalchemy.exc.ProgrammingError: (sqlite3.ProgrammingError) You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings. [SQL: u'INSERT INTO domains (domain, country, city, updated_date, expiration_date, registrar) VALUES (?, ?, ?, ?, ?, ?)'] [parameters: (u'<domain removed>', 'DE', 'Hohenm\xf6lsen', datetime.datetime(2013, 12, 30, 0, 0), datetime.datetime(2016, 1, 17, 0, 0), '<provider removed>')]

好像是这个字符串:

'Hohenm\xf6lsen'

为了解决这个问题,我使用了文本工厂

engine = create_engine('sqlite:///myDB.db')
engine.connect().connection.text_factory = str

我还尝试在我的 while 循环中使用 utf-8 从字典列表中读取:

with codecs.open(dictfile, 'rb', encoding='utf-8') as f:

我还检查了所有条目的变量类型,它们都是字符串,而不是数组或 blob。

我的完整代码可以在这里看到:

https://github.com/tripledown/domainfinder/blob/master/domainfinder.py

【问题讨论】:

标签: python sqlite sqlalchemy


【解决方案1】:

添加此行以分配 text_factory。它将字符串转换为 unicode 对象。

conn = GetSqliteConnection(db_path) conn.text_factory = lambda x: unicode(x, 'utf-8', 'ignore')

【讨论】:

    猜你喜欢
    • 2011-03-26
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多