gpt4 book ai didi

python - 使用 Python 从 MySQL 读取西里尔字母 utf-8 符号不正确

转载 作者:行者123 更新时间:2023-11-29 05:32:17 24 4
gpt4 key购买 nike

这是我的代码,它连接到数据库,并将俄语单词插入数据库:

import mysql.connector

if __name__ == '__main__':
try:
cnx = mysql.connector.connect(user='user', password='password',
host='123.123.123.123',
database='db_name',
charset='utf8',
collation='utf8_general_ci',
use_unicode=True)
except BaseException as ex:
print('Error: ' + str(ex))
cnx.close()
else:
print('Connections succesful!')
cnx.set_charset_collation('utf8', 'utf8_general_ci')
cursor = cnx.cursor()
print(cnx.charset)
cursor.execute("INSERT INTO table_name (column_name) values ('привет!')") #means 'Hello!' in russian
cursor.execute("SELECT * FROM test_referers")
print(cursor.fetchall())

这是我得到的:

Connection succesful!
utf8
(1, u'\u043f\u0440\u0438\u0432\u0435\u0442!')

这样的输出出现在 Python 解释器控制台和 Eclipse PyDev 中。

请帮忙

最佳答案

您的输出是有效的 Unicode。 Python 用 Unicode 转义值 (\uxxxx) 回显给你,因为该行由一个包含两个项目的元组组成;当打印一个元组时,它的内容被表示为 python 文字。

如果您使用以下代码:

print(cursor.fetchall()[1])

相反,它会打印:

привет!

您可以通过在 python 提示符下打印文字值来测试它:

>>> print u'\u043f\u0440\u0438\u0432\u0435\u0442!'
привет!

关于python - 使用 Python 从 MySQL 读取西里尔字母 utf-8 符号不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13727595/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com