2011-04-20 53 views
10

我有一個帶有Unicode列的SQLAlchemy模型。我有時會插入unicode值(u'Value'),但有時也會插入ASCII字符串。什麼是最好的方式去做這件事?當我插入ASCII字符串包含特殊字符的我得到這樣的警告:將字符串插入到SQLAlchemy Unicode列的正確方法

SAWarning: Unicode type received non-unicode bind param value ... 

如何避免這種情況?插入我不同類型的字符串的正確方法是什麼?

回答

5

THRE有幾個選項:

  1. 禁用與warnings.simplefilter('ignore', sqlalchemy.exc.SAWarning)所有SQLAlchemy的警告。
  2. 僅通過模塊和lineno或消息(例如, warnings.filterwarnings('ignore', '^Unicode type received non-unicode bind param value', sqlalchemy.exc.SAWarning)。使用String(convert_unicode=True)代替Unicode類型。
  3. 重新思考問題,並將您的代碼更改爲使用unicode,即使對於ASCII字符串。
+3

您attemping刪除的問題,而不是解決it.About數3:''sqlalchemy'官方文檔說使用'Unicode類型',但你說'使用String(convert_unicode = True)',我有同樣的問題,但我不認爲sqlalchemy解決'禁用警告',因爲它有'清潔代碼'不'髒'。 – PersianGulf 2013-09-06 05:59:51

0

你應該定義你的表類和構造這樣:

class User(declarative_base()): 
    _tablename__ = 'user' 
    name = Column(Unicode(200, convert_unicode=False)) 
    textfield = Column(UnicodeText(convert_unicode=False)) 

user = Table('user', MetaData(), 
Column('name', Unicode(200, convert_unicode=False), nullable=False), 
Column('textfield', UnicodeText(convert_unicode=False), nullable=False), 
) 

當然,你不應該忘記附上URI+"charset=utf8"create_engine function

相關問題