Python pymysql 链接数据库后,使用fetchall 打印结果中文出现乱码
时间: 2024-03-05 16:49:28 浏览: 18
出现乱码的原因是数据库和 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)
```
这样就可以避免中文乱码的问题了。
相关问题
python用pymysql链接数据库mysql
您可以使用`pymysql`库来连接MySQL数据库。以下是一个简单的示例代码:
```python
import pymysql
# 建立数据库连接
conn = pymysql.connect(
host='localhost', # 数据库主机地址
port=3306, # 数据库端口号,默认为3306
user='root', # 数据库用户名
password='password', # 数据库密码
db='mydatabase' # 要连接的数据库名
)
# 创建游标对象
cursor = conn.cursor()
# 执行SQL查询
sql = "SELECT * FROM mytable"
cursor.execute(sql)
# 获取查询结果
results = cursor.fetchall()
for row in results:
print(row)
# 关闭游标和数据库连接
cursor.close()
conn.close()
```
请确保您已经安装了`pymysql`库(可以使用`pip install pymysql`命令进行安装)。在代码中,您需要根据实际情况修改`host`、`port`、`user`、`password`和`db`等参数,以正确连接到您的MySQL数据库。然后,使用游标对象执行SQL查询,并通过`fetchall()`方法获取查询结果。最后,记得关闭游标和数据库连接。
希望对您有所帮助!如有任何问题,请随时提问。
python pymysql 连接数据库代码
当然,这是使用Python的pymysql库连接数据库的示例代码:
```python
import pymysql
# 连接数据库
conn = pymysql.connect(
host='localhost', # 数据库主机地址
port=3306, # 数据库端口号
user='root', # 数据库用户名
password='password', # 数据库密码
db='mydatabase' # 数据库名称
)
# 创建游标对象
cursor = conn.cursor()
# 执行SQL查询
cursor.execute("SELECT * FROM mytable")
# 获取查询结果
results = cursor.fetchall()
# 遍历结果
for row in results:
print(row)
# 关闭游标和连接
cursor.close()
conn.close()
```
请注意,你需要根据你的实际情况修改host、port、user、password和db参数,以及编写适合你的SQL查询语句。