【问题标题】:SQLAlchemy convert field using utf8SQLAlchemy 使用 utf8 转换字段
【发布时间】:2015-04-26 23:54:42
【问题描述】:

如何获得此 SQL 查询的等效 SQLAlchemy 语句?

select CONVERT(blobby USING utf8) as blobby from myTable where CONVERT(blobby USING utf8)="Hello";

其中 blobby 是一个 blob 类型的字段,必须将其分解为字符串。

我试过了

DBSession.query(myTable).filter(myTable.blobby.encode(utf-8)="Hello").first()

但不起作用。给出一个奇怪的错误

AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with myTable.blobby has an attribute 'encode'

此外,我尝试如下插入数据库:

que=myTable(blobby=str(x.blobby))
DBSession.add(que)

这也会返回一个错误提示

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

如果我像这样插入,这个错误就会消失

que=myTable(blobby=str(x))

但是插入的条目不支持外语值..

 EDIT:-

这就是我想要做的:

I have a list of utf-8 strings. The sqlalchemy column which I am
trying to insert my string has the property "convert_unicode" set to
true. Now, I have to insert these strings into my database without
loss of data. I need to preserve my multilingual characters which
worked fine when I fetched them as utf-8 from my Mysql database.
Trouble here is inserting them into SQLite using SQLalchemy.

请帮忙。谢谢和问候。

【问题讨论】:

    标签: mysql sql sqlite sqlalchemy


    【解决方案1】:

    这就是我为摆脱编码地狱和这个错误所做的事情。

    UnicodeDecodeError: 'ascii' codec
    can't decode byte 0xc4 in position
    10: ordinal not in range(128)
    

    我会逐步解释。

    1. 使用此命令:type(mydirtyunicodestring)

    2. 如果返回 那么这意味着您必须将其转换为 unicode 才能获得 摆脱错误。(字节字符串!!!!)

    3. 使用dirtystring.decode('utf-8') 或任何其他格式让您的类型出现在您那里 走。不会再出现 8 位编程错误 ProgrammingError) You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str).

    【讨论】:

    • 有时对 MySQL 的第 3 方扩展只会让事情变得更糟。 我希望一些 SQLAlchemy 专家能出现;生成什么 MySQL 代码并不明显;你能找到翻译吗?
    猜你喜欢
    • 2020-09-30
    • 2011-05-31
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    • 2012-03-13
    • 1970-01-01
    相关资源
    最近更新 更多