python 將中文寫入mysql

設置mysql中的charset是UTF-8的,然後在python代碼文件中設置#coding=utf-8。python從mysql獲取數據時,會將數據轉成unicode碼

# -*- coding: utf-8 -*-
import sys
import MySQLdb
import json

reload(sys)
sys.setdefaultencoding("utf-8")

db="xxx"
user="xxx"
passwd="xxx"
host="xxx"
port=zzz
charset="utf8"

dbconn = MySQLdb.connect(host=host, db=db, port=port, user=user, passwd=passwd, charset=charset, autocommit = True)
cursor = dbconn.cursor()

sql = 'select name,id from t1'
cursor.execute(sql)
rows = cursor.fetchall()
rows[0][0]  ### 類型爲unicode
str(rows[0][0])  ### 類型爲str,若要將中文插入Mysql中,使用這種方式

d = {"1": "我", "2": "們"}
json.dumps(d) ### 字典中的value會轉成unicode的形式,插入mysql時,不會顯示中文
json.dumps(d,ensure_ascii=False)  ### 若要將中文插入Mysql中,使用這種方式

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章