在用python做寫數據庫的客戶端時, 發生了寫入的中文數據爲亂碼的問題。經過查找資料,發現爲客戶端連接時的編碼方式問題。
使用MySQLdb包。
問題如下圖:
後來在連接數據庫時,進行了編碼方式的設置charset="utf8",就沒問題了。代碼段如下:
import MySQLdb
conn = MySQLdb.connect( host = '192.168.1.20', port = 3306, user = 'root', passwd = 'test', db = 'test', charset="utf8", ) cur = conn.cursor()
for i in range(REGION_NUM): mip = "0.0.0.%d"%(i) region = code_to_region[i].split('_') region_en = region[0] operator_en = region[1] region_cn = region_dict[region_en] operator_cn = operator_dict[operator_en] command = "INSERT INTO `test`.`qlljx_region` (`id`, `mip`, `region`, `province_en`, " \ "`province_cn`, `operator_en`, `operator_cn`) VALUES ('%d', '%s', '%s', '%s', '%s', '%s', '%s');" \ %(i, mip, code_to_region[i], region_en, region_cn, operator_en, operator_cn) print command cur.execute(command)
最後的結果如下圖: