我想将地址(类型 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
我尝试更改 address2
对于 address
在 mysql 查询中,以及许多其他尝试,但到目前为止我什么也没得到......
最佳答案
参见 Trouble with utf8 characters; what I see is not what I stored 中的“问号” :
- 要存储的字节未编码为 utf8/utf8mb4。 -- 大概
init_command
修复了这个问题。 - 数据库中的列是字符集 utf8(或 utf8mb4)。 -- 这似乎被打破了。
- 此外,请检查读取期间的连接是否为 UTF-8。
如果您遇到其他问题,请点击上面链接中的“测试数据”。
关于python - 如何将编码值存储到数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43438242/