解决python3链接mysql的乱码问题

#coding=utf-8 

import pymysql


# 打开数据库连接

db = pymysql.Connect(
    host='localhost',
    port=32768,
    user='root',
    passwd='123456',
    db='MyDbName',
    use_unicode=True,
    charset='utf8'
    )


# 使用cursor()方法获取操作游标 
cursor = db.cursor()

# f = open('te.txt','w+',encoding='utf8')

# SQL 查询语句
sql = "SELECT * FROM Person \
       WHERE Id < %s" % (5)
try:
   # 执行SQL语句
   cursor.execute(sql)
   # 获取所有记录列表
   results = cursor.fetchall()
   for row in results:
      Id = row[1]
      Name = row[0]
      # f.write(Name)
      # 打印结果
      print("Id=%s,name=%s" % \
             (Id, Name.encode('latin-1').decode('gbk')))
except  Exception as err:
   print(err)

# 关闭数据库连接
db.close()


作者:spike

分类: Python

创作时间:2023-06-25

更新时间:2024-12-08

联系方式放在中括号之中例如[[email protected]],回复评论在开头加上标号例如:#1