Python pymysql 链接数据库后,使用fetchall 打印结果中文出现乱码
时间: 2024-03-05 15:49:28 浏览: 144
出现乱码的原因是数据库和 Python 之间的编码不一致。可以尝试以下两种方法解决:
1. 在建立数据库连接时设置编码
```python
import pymysql
db = pymysql.connect(host='localhost', user='root', password='password', database='test', charset='utf8')
cursor = db.cursor()
cursor.execute('SELECT * FROM table')
result = cursor.fetchall()
print(result)
```
2. 在执行查询语句后设置编码
```python
import pymysql
db = pymysql.connect(host='localhost', user='root', password='password', database='test')
cursor = db.cursor()
cursor.execute('SET NAMES utf8mb4')
cursor.execute('SELECT * FROM table')
result = cursor.fetchall()
print(result)
```
这样就可以避免中文乱码的问题了。
阅读全文
相关推荐


















