如何处理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 相关文章推荐
用Python进行行为驱动开发的入门教程
Apr 23 Python
Python实例一个类背后发生了什么
Feb 09 Python
python3处理含有中文的url方法
May 10 Python
Python中使用logging和traceback模块记录日志和跟踪异常
Apr 09 Python
谈一谈基于python的面向对象编程基础
May 21 Python
使用OpenCV实现仿射变换—旋转功能
Aug 29 Python
Flask框架路由和视图用法实例分析
Nov 07 Python
python可视化text()函数使用详解
Feb 11 Python
Python3.7实现验证码登录方式代码实例
Feb 14 Python
django日志默认打印request请求信息的方法示例
May 17 Python
Python爬取网站图片并保存的实现示例
Feb 26 Python
Python利用FlashText算法实现替换字符串
Mar 31 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生成圆角图片的方法
2015/04/07 PHP
laravel手动创建数组分页的实现代码
2018/06/07 PHP
List the UTC Time on a Computer
2007/06/11 Javascript
AngularJS的表单使用详解
2015/06/17 Javascript
jQuery满屏焦点图左右滚动特效代码分享
2015/09/07 Javascript
js实现遍历含有input的table实例
2015/12/07 Javascript
利用JS轻松实现获取表单数据
2016/12/06 Javascript
nodejs基础知识
2017/02/03 NodeJs
正则验证小数点后面只能有两位数的方法
2017/02/28 Javascript
详解用webpack2.0构建vue2.0超详细精简版
2017/04/05 Javascript
jquery.form.js异步提交表单详解
2017/04/25 jQuery
bootstrap table表格使用方法详解
2017/04/26 Javascript
Node.js之readline模块的使用详解
2019/03/25 Javascript
vue实现滑动到底部加载更多效果
2020/10/27 Javascript
Vue 中获取当前时间并实时刷新的实现代码
2020/05/12 Javascript
three.js 利用uv和ThreeBSP制作一个快递柜功能
2020/08/18 Javascript
Vue页面渲染中key的应用实例教程
2021/01/12 Vue.js
Python中使用logging模块代替print(logging简明指南)
2014/07/09 Python
pandas 选择某几列的方法
2018/07/03 Python
PyCharm设置护眼背景色的方法
2018/10/29 Python
python批量从es取数据的方法(文档数超过10000)
2018/12/27 Python
Python3几个常见问题的处理方法
2019/02/26 Python
Python判断远程服务器上Excel文件是否被人打开的方法
2020/07/13 Python
Myprotein台湾官方网站:全球领先的运动营养品牌
2018/12/10 全球购物
英国在线药房:Express Chemist
2019/03/28 全球购物
青年创业培训欢迎词
2014/01/08 职场文书
自我鉴定书面格式
2014/01/13 职场文书
幼儿园新学期寄语
2014/01/18 职场文书
创业计划书如何编写
2014/02/06 职场文书
应聘销售主管的求职信
2014/04/26 职场文书
尊老爱亲美德少年事迹材料
2014/08/14 职场文书
党委班子剖析材料
2014/08/21 职场文书
2014年前台文员工作总结
2014/12/08 职场文书
会议开幕致辞怎么写
2016/03/03 职场文书
PostgreSQL事务回卷实战案例详析
2022/03/25 PostgreSQL
Android 中的类文件和类加载器详情
2022/06/05 Java/Android