歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python調用MySQLdb插入中文亂碼的問題

Python調用MySQLdb插入中文亂碼的問題

日期:2017/3/1 10:22:52   编辑:Linux編程
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. import MySQLdb
  4. def main():
  5. fullname = "趙錢孫李"
  6. conn = MySQLdb.connect(host='localhost', user='root',passwd='123', db='account', charset='utf8') # OK
  7. #conn = MySQLdb.connect(host='localhost', user='root',passwd='123', db='account') # Error!!!
  8. cursor = conn.cursor()
  9. cursor.execute("insert into account (username,password) values ('%s','%s')" % (fullname, "111"))
  10. conn.commit()
  11. cursor.close()
  12. conn.close()
  13. if __name__ == "__main__":
  14. main()

如果從終端查詢到數據庫中的中文是亂碼,那麼在連接時給出charset參數即可(當然數據庫和表必須全部都是utf-8的)。
否則默認插入的字符應該是latin-1的(用fullname.decode('utf8')時報該錯誤)。

然後將從數據庫中讀取的中文輸出到網頁,如果沒有任何內容顯示,加入以下代碼可解決:

  1. import sys
  2. reload(sys)
  3. sys.setdefaultencoding('utf-8')
Python內部處理編碼默認是ascii的: print sys.getdefaultencoding()
Copyright © Linux教程網 All Rights Reserved