我决定在Python3中首次使用Django1.7。
我需要能够使用包含latin1
数据的遗留utf8
数据库。我知道这很糟糕,但是数据库太大了,根本不可能改变。所以我试着跟随:
DATABASES = {
'ENGINE' : 'django.db.backends.mysql', // using MySQL-python fork with support for py3
...
'OPTIONS' : {
'init_command': "SET character_set_results = 'latin1'",
#'read_default_file': '/etc/my.cnf.d/client.cnf', // I've also tried this one
}
}
我还尝试了来自Oracle的python mysql连接器,设置如下
DATABASES = {
'ENGINE' : 'mysql.connector.django', // using MySQL-python fork with support for py3
'OPTIONS' : {
'option_files': ['/etc/my.cnf.d/client.cnf'],
}
}
/etc/my.cnf.d/client.cnf公司
[client]
init-command='SET character_set_results = "latin1"'
# password, host, username
在这两种情况下,我都可以连接到数据库,但Django似乎将character_set_结果设置回utf8。
我试过跟随
from django.db import connection
with connection.cursor() as c:
// I expect variable to be 'latin1'
c.execute("show variables like 'character_set_results%'")
c.fetchone() // returns ('character_set_results', 'utf8')
// here I try to set it manually
c.execute("SET character_set_results = 'latin1'")
c.execute("show variables like 'character_set_results%'")
c.fetchone() // returns ('character_set_results', 'latin1') // now it's OK
我确信django使用
client.cfg
文件并更正[section]
,因为它包含用户名/密码并且成功连接到数据库当我在使用相同配置文件的linux终端中使用
mysql
命令时,一切都按预期工作所以我猜Django以某种方式强制
character_set_results
变量成为utf8
。有可能吗?有什么办法可以解决这个问题吗?非常感谢你
最佳答案
我终于弄明白了(我不知道为什么我总是在发布给SO后的一段时间内找到解决方案)
from django.db.backends.signals import connection_created
def connection_setup(**kwargs):
conn = kwargs['connection']
with conn.cursor() as cursor:
cursor.execute("SET character_set_results = 'latin1'")
cursor.close()
我以前用过甲骨文的
python-mysql-connector
但它与
RuntimeError: maximum recursion depth exceeded in comparison
py3分支一起工作。我想这可能是我要报告的MySQL-driver
或python-mysql-connector
中的一个错误。也许这能帮上忙。关于python - 无法将character_set_results设置为latin1,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25683570/