我使用pymysql插入数据(中文)。当我使用fetchall并打印结果时,代码运行正常,结果也正常。然而,当我手动登录mysql时,当我使用“select*fromtb”时,我发现数据是乱码。字符编码应该是可以的,因为当我手动将中文插入一个新表时它可以工作。
有什么建议吗?
当我运行“show create database taoya”和“show create table tb”时,我检查了代码是“utf-8”。
变量如下:
+--------------------------------------+--------------------------------+
| Variable_name | Value |
+--------------------------------------+--------------------------------+
| character_set_client | utf8mb4 |
| character_set_connection | utf8mb4 |
| character_set_database | utf8mb4 |
| character_set_filesystem | binary |
| character_set_results | utf8mb4 |
| character_set_server | utf8mb4 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql-8.0/charsets/ |
| validate_password.special_char_count | 1 |
+--------------------------------------+--------------------------------+
代码如下:
mysql= pymysql.connect(host=xx,user=xx,password=xxx, db="taoya",charset="utf8mb4")
try:
with mysql.cursor() as cur:
# cur.execute("set names 'utf8'")
cur.execute("DROP TABLE IF EXISTS TB")
sql = '''CREATE TABLE IF NOT EXISTS TB(
Commody CHAR(70) NOT NULL,
Store CHAR(20),
Address CHAR(20),
Price CHAR(20),
Paid CHAR(40))
DEFAULT CHARSET=utf8mb4
'''
cur.execute(sql)
insertsql="INSERT INTO TB (Commody,Store,Address, Price,Paid) VALUES (%s, %s,%s,%s,%s)"
data= ("牛 啊","hi","你好","$33","3人")
cur.execute(insertsql,data)
cur.execute("SELECT * FROM TB;")
result = cur.fetchall()
print(result)
mysql.commit()
finally:
mysql.close()
结果正常:
(('牛 啊', 'hi', '你好', '$33', '3人'),)
从mysql方面:
mysql> select * from TB;
+------------+-------+---------+-------+------+
| Commody | Store | Address | Price | Paid |
+------------+-------+---------+-------+------+
| 鐗涢€鍟 | hi | 浣犲ソ | $33 | 3浜 |
+------------+-------+---------+-------+------+
1条答案
按热度按时间m1m5dgzv1#
Python2
linux?
mysql配置: