python中进行sql查询出现乱码怎么解决
发布时间:2026-04-12 15:36:35

通过Python查询数据库中的数据时,数据汇呈现乱码,只需在连接串中指定数据编码,如“utf8”、“GBK”即可:
importpymysql
db=pymysql.connect(host="localhost",user="root",password="root",database="school_schema",charset="GBK")
cursor=db.cursor()
sqlstr="SELECT*FROMschool_schema.course;"try:
cursor.execute(sqlstr)
courses=cursor.fetchall()except:
print("错误的数据读取")else:
print(courses)
db.close()pymysql.Connect()参数说明:
host(str): MySQL服务器地址
port(int): MySQL服务器端口号
user(str): 用户名
passwd(str): 密码
db(str): 数据库名称
charset(str): 连接编码
请关注Python视频教程栏目,了解更多Python知识。
