Django admin 保存unicode報錯 解決辦法

如題,原因是創建數據庫和表的時候 默認字符集設置的問題,修改即可。

下面是批量修改數據庫所有表的列的 默認字符集 Python 腳本

#! /usr/bin/env python
import MySQLdb
host='localhost'
password='your passwd'
user='your user name'
dbname='your database naem'

db=MySQLdb.connect(host=host,user=user,passwd=password,db=dbname)
cursor=db.cursor()
cursor.execute("ALTER DATABASE `%s` CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'" % dbname)

sql = "SELECT DISTINCT(table_name) FROM information_schema.columns WHERE table_schema = '%s'" % dbname
cursor.execute(sql)

results=cursor.fetchall()
for row in results:
	#print row[0]
	sql="ALTER TABLE %s convert to character set DEFAULT COLLATE DEFAULT " % (row[0])
	cursor.execute(sql)
db.close()
python 運行即可。

MySQL 版本爲 5.5,其他版本沒有試。


打開MySQL 可以查看修改後的表的字符集

mysql> SELECT T.table_name, T.table_collation, CCSA.character_set_name FROM information_schema.`TABLES` T,
    -> information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` CCSA
    -> WHERE CCSA.collation_name = T.table_collation
    -> AND T.table_schema = "databasename";
+----------------------------+-----------------+--------------------+
| table_name                 | table_collation | character_set_name |
+----------------------------+-----------------+--------------------+
| auth_group_permissions     | utf8_unicode_ci | utf8               |
| auth_permission            | utf8_unicode_ci | utf8               |
| auth_user                  | utf8_unicode_ci | utf8               |
| auth_user_groups           | utf8_unicode_ci | utf8               |
| auth_user_user_permissions | utf8_unicode_ci | utf8               |
| table_name1                | utf8_unicode_ci | utf8               |
| table_name2                | utf8_unicode_ci | utf8               |
| table_name3                | utf8_unicode_ci | utf8               |
| table_name4                | utf8_unicode_ci | utf8               |
| django_admin_log           | utf8_unicode_ci | utf8               |
| django_content_type        | utf8_unicode_ci | utf8               |
| django_session             | utf8_unicode_ci | utf8               |
+----------------------------+-----------------+--------------------+
14 rows in set (0.03 sec)



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