如何处理Python3.4 使用pymssql 乱码问题


Posted in Python onJanuary 08, 2016

在项目中发现这样一个问题:sqlserver数据库编码为gbk,使用python3.4+pymssql 查询,中文乱码,经过一番思考问题解决,下面把解决办法分享给大家:

conn = pymssql.connect(host="192.168.122.141", 
port=1433, 
user="myshop", 
password="oyf20140208HH", 
database="mySHOPCMStock", 
charset='utf8', 
as_dict=True) cur = conn.cursor()sql = "select top 10 [ID],[Name] from [User]"cur.execute(sql)list = cur.fetchall()for row in list: print(row["ID"],row["Name"].encode('latin-1').decode('gbk'))

接下来给大家介绍python 使用pymssql连接sql server数据库

#coding=utf-8 
#!/usr/bin/env python
#-------------------------------------------------------------------------------
# Name: pymssqlTest.py
# Purpose: 测试 pymssql库,该库到这里下载:http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql
#
# Author: scott
#
# Created: 04/02/2012
#-------------------------------------------------------------------------------
import pymssql
class MSSQL:
"""
对pymssql的简单封装
pymssql库,该库到这里下载:http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql
使用该库时,需要在Sql Server Configuration Manager里面将TCP/IP协议开启
用法:
"""
def __init__(self,host,user,pwd,db):
self.host = host
self.user = user
self.pwd = pwd
self.db = db
def __GetConnect(self):
"""
得到连接信息
返回: conn.cursor()
"""
if not self.db:
raise(NameError,"没有设置数据库信息")
self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8")
cur = self.conn.cursor()
if not cur:
raise(NameError,"连接数据库失败")
else:
return cur
def ExecQuery(self,sql):
"""
执行查询语句
返回的是一个包含tuple的list,list的元素是记录行,tuple的元素是每行记录的字段
调用示例:
ms = MSSQL(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics")
resList = ms.ExecQuery("SELECT id,NickName FROM WeiBoUser")
for (id,NickName) in resList:
print str(id),NickName
"""
cur = self.__GetConnect()
cur.execute(sql)
resList = cur.fetchall()
#查询完毕后必须关闭连接
self.conn.close()
return resList
def ExecNonQuery(self,sql):
"""
执行非查询语句
调用示例:
cur = self.__GetConnect()
cur.execute(sql)
self.conn.commit()
self.conn.close()
"""
cur = self.__GetConnect()
cur.execute(sql)
self.conn.commit()
self.conn.close()
def main():
## ms = MSSQL(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics")
## #返回的是一个包含tuple的list,list的元素是记录行,tuple的元素是每行记录的字段
## ms.ExecNonQuery("insert into WeiBoUser values('2','3')")
ms = MSSQL(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics")
resList = ms.ExecQuery("SELECT id,weibocontent FROM WeiBo")
for (id,weibocontent) in resList:
print str(weibocontent).decode("utf8")
if __name__ == '__main__':
main()

三水点靠木提醒大家需要注意事项:

使用pymssql进行中文操作时候可能会出现中文乱码,我解决的方案是:

文件头加上 #coding=utf8

sql语句中有中文的时候进行encode

insertSql = "insert into WeiBo([UserId],[WeiBoContent],[PublishDate]) values(1,'测试','2012/2/1')".encode("utf8")

连接的时候加入charset设置信息

pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8")

Python 相关文章推荐
使用Node.js和Socket.IO扩展Django的实时处理功能
Apr 20 Python
python使用分治法实现求解最大值的方法
May 12 Python
Python实现基于二叉树存储结构的堆排序算法示例
Dec 08 Python
浅谈numpy数组中冒号和负号的含义
Apr 18 Python
Python代码打开本地.mp4格式文件的方法
Jan 03 Python
PyCharm在新窗口打开项目的方法
Jan 17 Python
对Python3 goto 语句的使用方法详解
Feb 16 Python
如何在python中写hive脚本
Nov 08 Python
python快速排序的实现及运行时间比较
Nov 22 Python
Python selenium自动化测试模型图解
Apr 15 Python
PyTorch 导数应用的使用教程
Aug 31 Python
Python+Selenium随机生成手机验证码并检查页面上是否弹出重复手机号码提示框
Sep 21 Python
Python argv用法详解
Jan 08 #Python
详解Python爬虫的基本写法
Jan 08 #Python
黑科技 Python脚本帮你找出微信上删除你好友的人
Jan 07 #Python
星球大战与Python之间的那些事
Jan 07 #Python
python高手之路python处理excel文件(方法汇总)
Jan 07 #Python
Python解析最简单的验证码
Jan 07 #Python
Python中http请求方法库汇总
Jan 06 #Python
You might like
PHP处理excel cvs表格的方法实例介绍
2013/05/13 PHP
ThinkPHP采用原生query实现关联查询left join实例
2014/12/02 PHP
ThinkPHP框架结合Ajax实现用户名校验功能示例
2019/07/03 PHP
PHP中非常有用却鲜有人知的函数集锦
2019/08/17 PHP
php实现根据身份证获取精准年龄
2020/02/26 PHP
Javascript下判断是否为闰年的Datetime包
2010/10/26 Javascript
javascript实现div的显示和隐藏的小例子
2013/06/25 Javascript
jquery validate添加自定义验证规则(验证邮箱 邮政编码)
2013/12/04 Javascript
基于JQuery实现的Select级联
2014/01/27 Javascript
javascript事件模型实例分析
2015/01/30 Javascript
jQuery中ajax错误调试分析
2016/12/01 Javascript
Less 安装及基本用法
2018/05/05 Javascript
JS 使用 window对象的print方法实现分页打印功能
2018/05/16 Javascript
webpack项目使用eslint建立代码规范实现
2019/05/16 Javascript
小程序实现搜索框
2020/06/19 Javascript
node.js中npm包管理工具用法分析
2020/02/14 Javascript
javascript中的offsetWidth、clientWidth、innerWidth及相关属性方法
2020/05/14 Javascript
[01:07:20]DOTA2-DPC中国联赛 正赛 Dynasty vs XG BO3 第二场 2月2日
2021/03/11 DOTA
用Python编写一个简单的Lisp解释器的教程
2015/04/03 Python
Python面向对象程序设计类的多态用法详解
2019/04/12 Python
Django ImageFiled上传照片并显示的方法
2019/07/28 Python
Django框架创建mysql连接与使用示例
2019/07/29 Python
Pandas-Cookbook 时间戳处理方式
2019/12/07 Python
python模拟斗地主发牌
2020/04/22 Python
Python3批量创建Crowd用户并分配组
2020/05/20 Python
pycharm 快速解决python代码冲突的问题
2021/01/15 Python
html5开发之viewport使用
2013/10/17 HTML / CSS
佐卡伊官网:中国知名珠宝品牌
2017/02/05 全球购物
美国现代家具购物网站:LexMod
2019/01/09 全球购物
在使用非全零作为空指针内部表达的机器上, NULL是如何定义
2014/11/09 面试题
什么是Rollback Segment
2013/04/22 面试题
总经理职责
2013/12/22 职场文书
工作失职检讨书范文
2014/01/16 职场文书
食品安全标语
2014/06/07 职场文书
奥巴马经典演讲稿
2014/09/13 职场文书
海上钢琴师观后感
2015/06/03 职场文书