2014-07-25 25 views
0

我在使用SQLAlchemy在Flask上運行的表單中意外地使用了非ascii字符的錯誤。基本上,我不使用ASCII連字符,而是使用unicode en-dash 。我現在想回去並用數據庫中的連字符替換所有出現的連字符。在Flask上使用SQLAlchemy替換所有行的字符

比方說,我有一個用戶表,我試圖改變的列名爲occupation。我可以找出哪些條目在我的數據庫中有無效字符,因爲當我運行:

User.query.get(id) 

如果用戶有一個無效的ASCII字符,則返回

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 167: ordinal not in range(128) 

因此,如何能我用數據庫中所有行的occupation列中的連字符替換所有出現的連字符?

+0

你有沒有試過做這樣的事情來執行查詢? http://stackoverflow.com/questions/10819192/sqlalchemy-result-for-utf-8-column-is-of-type-str-why – pgorsira

+0

然後,你可以只替換每條記錄中的連字符並堅持更改。 – pgorsira

回答

0

我能夠通過在我的數據庫中的所有條目上運行腳本並用錯誤字符替換這些腳本來解決此問題。

from user.models import * 
for u in User.query.all(): 
    # \u2013 is unicode for en-dash 
    if u"\u2013" in u.occupation: 
     # replace with normal hyphen 
     u.occupation = u.occupation.replace(u"\u2013", "-") 
     db.session.commit() 
相關問題