今天嘗試着用 Python 寫了個腳本試着連接 mysql 數據庫,並查詢里邊的數據,不過最終查詢結果中文字符變成了ascii格式。
代碼如下:
#!/usr/bin/python #encoding=utf-8 import MySQLdb import json db = MySQLdb.connect(host='xxx.xxx.xx.xxx',port=3306,user='name',passwd='pwd',db='my_database_name') cursor = db.cursor() sql = "select * from platform_temp" aa=cursor.execute(sql) info = cursor.fetchmany(aa) for i in info: print i db.close()
查詢結果如下:
針對上述出現的問題,對編輯器Pycharm的環境都進行了設置為utf-8格式,但是結果還都如上圖所示。
最后通過查詢本地window控制台字節碼格式,為ascii,如下圖所示:
In[5]: import sys In[6]: print(sys.getdefaultencoding()) ascii
再次對上述代碼進行修改,結果還是如此,代碼如下:
#!/usr/bin/python #encoding=utf-8 import MySQLdb import json db = MySQLdb.connect(host='xxx.xxx.xxx.xxx',port=3306,user='name',passwd='pwd',db='my_database_name') cursor = db.cursor() sql = "select * from platform_temp" aa=cursor.execute(sql) info = cursor.fetchmany(aa) for i in info: print str(i).encode('utf-8') print str(i).decode('utf-8') print str(i).decode('utf-8').encode('utf-8') db.close()
最后通過嘗試將 json 模塊導入,利用其 dumps 方法,問題得到解決,代碼如下圖所示:
#!/usr/bin/python #encoding=utf-8 import MySQLdb import json db = MySQLdb.connect(host='xxx.xxx.xxx.xxx',port=3306,user='name',passwd='pwd',db='my_database_name') cursor = db.cursor() sql = "select * from platform_temp" aa=cursor.execute(sql) info = cursor.fetchmany(aa) for i in info: # print str(i).encode('utf-8') # print str(i).decode('utf-8') # print str(i).decode('utf-8').encode('utf-8') print json.dumps(i, encoding='UTF-8', ensure_ascii=False)
查詢結果如下所示:
問題解決,結束。
實例配置:
def get_one(self): #准備sql sql = 'SELECT * FROM `news` WHERE `types` = %s ORDER BY `created_at` DESC;' # 找到cursor cursor = self.conn.cursor() cursor.execute('SET NAMES UTF8') # 執行sql cursor.execute(sql, ('百家', )) # 拿到結果 rest = cursor.fetchmany() for r in rest: print json.dumps(r, encoding='UTF-8', ensure_ascii=False) # 處理數據 cursor.close() self.close_conn()
[root@centos-01 python]# python test001.py [2, "男子長得像\"祁同偉\"挨打 打人者:為何加害檢察官", "新聞內容", "百家", "/static/img/news/02.png", null, 0, null, 1]
python3 可以用 pymysql 連接數據庫 , 沒有中文亂碼的問題