如何处理Python3.4 使用pymssql 乱码问题
在项目中发现这样一个问题: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="selecttop10[ID],[Name]from[User]"cur.execute(sql)list=cur.fetchall()forrowinlist:print(row["ID"],row["Name"].encode('latin-1').decode('gbk'))
接下来给大家介绍python使用pymssql连接sqlserver数据库
#coding=utf-8
#!/usr/bin/envpython
#-------------------------------------------------------------------------------
#Name:pymssqlTest.py
#Purpose:测试pymssql库,该库到这里下载:http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql
#
#Author:scott
#
#Created:04/02/2012
#-------------------------------------------------------------------------------
importpymssql
classMSSQL:
"""
对pymssql的简单封装
pymssql库,该库到这里下载:http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql
使用该库时,需要在SqlServerConfigurationManager里面将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()
"""
ifnotself.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()
ifnotcur:
raise(NameError,"连接数据库失败")
else:
returncur
defExecQuery(self,sql):
"""
执行查询语句
返回的是一个包含tuple的list,list的元素是记录行,tuple的元素是每行记录的字段
调用示例:
ms=MSSQL(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics")
resList=ms.ExecQuery("SELECTid,NickNameFROMWeiBoUser")
for(id,NickName)inresList:
printstr(id),NickName
"""
cur=self.__GetConnect()
cur.execute(sql)
resList=cur.fetchall()
#查询完毕后必须关闭连接
self.conn.close()
returnresList
defExecNonQuery(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()
defmain():
##ms=MSSQL(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics")
###返回的是一个包含tuple的list,list的元素是记录行,tuple的元素是每行记录的字段
##ms.ExecNonQuery("insertintoWeiBoUservalues('2','3')")
ms=MSSQL(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics")
resList=ms.ExecQuery("SELECTid,weibocontentFROMWeiBo")
for(id,weibocontent)inresList:
printstr(weibocontent).decode("utf8")
if__name__=='__main__':
main()
毛票票提醒大家需要注意事项:
使用pymssql进行中文操作时候可能会出现中文乱码,我解决的方案是:
文件头加上#coding=utf8
sql语句中有中文的时候进行encode
insertSql="insertintoWeiBo([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")