web.py+mysql插入中文提示query = query.encode(charset) UnicodeEncodeError: 'latin-1' codec can't encode characters in position 86-100

來源:互聯網
上載者:User

標籤:

對於中文編碼的問題,總會出現各種各樣噁心的錯誤,還不知道應該怎麼解決,首先,你從最開頭就應該關注編碼問題,盡量保證所有的編碼方式都是一致的

用python+web.py+mysql來寫程式,首先要保證如下幾個部分的編碼都是對滴

主要包括如下幾個部分:

1:python 寫的程式, 統一用 utf-8 ,以及重新載入utf-8

2: web.py 的模板, 也就是html程式
  統一儲存格式為utf-8 , 並且html 申明 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
3:Mysql 建立資料庫,資料庫使用UTF-8(包括建資料庫和建表的時候,把編碼格式都使用utf8)

但最後還是會有這樣的問題,錯誤提示如下:

[2015-06-02 10:35:38] [INFO] self.pool <DBUtils.PooledDB.PooledDB instance at 0x028E7E18>
[2015-06-02 10:35:38] [INFO] conn:
[2015-06-02 10:35:38] [INFO] <DBUtils.PooledDB.PooledDedicatedDBConnection instance at 0x02ADA580>
[2015-06-02 10:35:38] [INFO] cursor:
[2015-06-02 10:35:38] [INFO] <MySQLdb.cursors.Cursor object at 0x029EED10>
[2015-06-02 10:35:38] [ERROR] DB_execute error: Traceback (most recent call last):
File "E:\code\mid-project-2015-6-2\dailypaper\model.py", line 131, in execute
cursor.execute(sql)
File "C:\Python26\lib\site-packages\dbutils-1.1-py2.6.egg\DBUtils\SteadyDB.py", line 552, in tough_method
result = method(*args, **kwargs) # try to execute
File "C:\Python26\lib\site-packages\MySQLdb\cursors.py", line 149, in execute
query = query.encode(charset)
UnicodeEncodeError: ‘latin-1‘ codec can‘t encode characters in position 86-100: ordinal not in range(256)

然後能看到的是cursors.py裡面的query = query.encode(charset),那麼應該是這個charset的原因,直接把charset改成‘utf-8‘就行了,query = query.encode(‘utf-8‘)

然後就可以插入,並且可以select出來正確的值,然後從網頁上也能夠看到啦!!!

web.py+mysql插入中文提示query = query.encode(charset) UnicodeEncodeError: 'latin-1' codec can't encode characters in position 86-100

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.