我想将地址(类型string
)存储到数据库字段(类型VARCHAR
)中。问题是有时地址有非 ASCII字符,所以我做了下一个:
在我的 .py 文件中
import sys
reload(sys)
sys.setdefaultencoding('utf8')
# Other imports...
# The connection with the DB
conn = MySQLdb.connect(host="127.0.0.1", user="myUser", passwd="myPass", db="myDB", charset='utf8', init_command='SET NAMES UTF8')
# More code here...
address2 = address.encode('utf-8')
print "\nTHE ADDRESS TYPE IS -> ", type(address), "\n"
print "\nTHE ADDRESS IS -> ", address, "\n"
print "\nTHE ADDRESS2 IS -> ", address2, "\n"
self.conn.cursor().execute("""INSERT INTO myTable (BLA, BLA, ADDRESS) VALUES (%s, %s, %s)""", (bla, bla, address2))
# The rest of the code...
所以当我运行代码时,我得到以下内容prints
:
THE ADDRESS TYPE IS -> <type 'str'>
THE ADDRESS IS -> Francesc Aragó, 2, 07872 Es Caló, España
THE ADDRESS2 IS -> Francesc Aragó, 2, 07872 Es Caló, España
但是当我转到数据库中的表并访问该字段时,我得到了这个
Francesc Arag?, 2, 07872 Es Cal?, Espa?a
我已经尝试更改mysql 查询中的address2
foraddress
以及许多其他尝试,但到目前为止我一无所获......
请参阅utf8 字符问题中的“问号” ;我看到的不是我存储的:
init_command
修复了这个。如果您还有其他问题,请按照上述链接中的“测试数据”进行操作。
这里的 Python 提示:http : //mysql.rjweb.org/doc.php/charcoll#python
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句