python连接数据库设置编码_python3连接MSSQL数据库 中文乱码怎么解决?

在别的地方看到的,找了很久,给你看下吧,亲测可解决乱码问题

下面这个例子是显示表的内容,类似于SQL中的select * from [table]。其中有的字段是中文,将用于getCode来进行转码。

import sys

import pymssql

import types

#sys.setdefaultencoding(utf-8)

def str2bin(strText):

b = bytes((ord(i) for i in strText))

return b

#codec can be 'gb2312','utf8' etc

def getCode(strText,codec):

b = bytes((ord(i) for i in strText))

return b.decode(codec)

conn=pymssql.connect(host="IP\SQLEXPRESS",user="user",password="password",database="stock")

#conn=pymssql.connect(host="*",database="*",trusted=True)

cur=conn.cursor()

#cur.execute(u"SELECT * FROM dbo.t_Task".encode('gb2312')) #如果你的表名是中文

cur.execute(u"SELECT * FROM dbo.t_Task")

row = cur.fetchone()

while row:

for col in row:

if(isinstance(col,str)):

print(getCode(col,'gb2312'),end=' ')

else:

print(col,end=' ')

print()

row = cur.fetchone()

conn.close()

python2.x中字符串有decode方法,而python3.x已经取消了,因为3.x中字符类型缺少就是unicode的。所以需要将非unicode字符串转成2进制,就是函数 str2bin(strText)的作用。其他自己体会。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值