SQLAlchemy使用utf8转换字段

时间:2015-02-25 04:53:31

标签: mysql sql sqlite sqlalchemy

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

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

其中 blobby 是一个blob类型字段,必须是unblobbed到字符串。

我试过这个

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.

请帮忙。谢谢和问候。

1 个答案:

答案 0 :(得分:0)

所以这就是我为摆脱编码地狱所做的一切,以及这个错误。

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')     或任何其他格式让你的类型到那里     走。不再有ProgrammingError) You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str).
  4. 的8位编程错误