关于PYTHON用PYODBC连接SQLSERVER的封装

【环境】Windows10 64bit、Python 2.7 64bit、Pycharm 2017.1 Amd64、SqlServer 2008

【安装】pyodbc的安装我这里就不说了,找度娘

【难点】主要是查询出来的中文以及Sql语句中包含中文的乱码问题

转载请注明出处:http://blog.csdn.net/humanbeng/article/details/75620169

下面贴上代码DBHelper.py

#coding:utf-8
import pyodbc

class DBHelper(object):

    def __init__(self, serverIp, port, dbName, uid, pwd):
        conn_info = 'DRIVER={SQL Server};DATABASE=%s;SERVER=%s,%s;UID=%s;PWD=%s' % (dbName, serverIp, port, uid, pwd)
        self.connection = pyodbc.connect(conn_info, unicode_results=True)
        self.cursor = self.connection.cursor()

    def __del__(self):
        if self.cursor:
            self.cursor.close()
            self.cursor = None
            print(self.cursor, '__del__ cursor closed')
        if self.connection:
            self.connection.close()
            self.connection = None

    def destroy(self):
        if self.cursor:
            print(self.cursor, 'destroy cursor closed')
            self.cursor.close()
            self.cursor = None
        if self.connection:
            self.connection.close()
            self.connection = None

    # 获取全部查询结果
    def queryAll(self, qryStr):
        print(qryStr.decode('gbk'))
        self.cursor.execute(qryStr)
        return self.cursor.fetchall()

    # 获取前maxcnt条查询结果
    def querySome(self, qryStr, maxCount):
        self.cursor.execute(qryStr)
        return self.cursor.fetchmany(maxCount)

    #获取分页查询结果
    def queryPage(self, qryStr, skipCnt, pageSize):
        self.cursor.execute(qryStr)
        self.cursor.skip(skipCnt)
        return self.cursor.fetchmany(pageSize)

    #获取查询条数
    def count(self, sql):
        self.cursor.execute(sql)
        return self.cursor.fetchone()[0]

    #执行语句,包括增删改,返回变更数据数量
    def execute(self, sql):
        count = self.cursor.execute(sql).rowcount
        self.connection.commit()
        return count

下面是测试程序DBHelperTest.py,语句如果有中文请先decode成GBK编码

#coding:utf-8
import traceback

from DBHelper import  DBHelper

helper = DBHelper('*.*.*.*', 'port', 'dbname', 'username', 'password')

try:
    sql = u'select * from T_CharityReport where Title like \'%测试%\''
    row = helper.queryAll(sql.encode('GBK'))
    for i in row:
        # 这里如果查询出来的字段有中文,就必须单个查询出来,
        # 查询出来的默认返回的GBK的编码,但是在DBHelper里连接是设置了unicode_results=True
        # 查询出的编码是Unicode,所以这里就不用执行i[1].decode('GBK')操作了
        print i[0], i[1], i[2], i[3], i[4], i[5]

    sql = u'select * from T_CharityReport where Title = \'test\''
    row = helper.querySome(sql.encode('GBK'), 1)
    for i in row:
        print i[0], i[1], i[2], i[3], i[4], i[5]

except Exception as e:
    # 调试时打开如下,方便跟踪异常出处
    print 'str(Exception):\t', str(Exception)
    print 'str(e):\t\t', str(e)
    print 'e.message:\t', e.message
    print 'traceback.print_exc():\n%s' % traceback.print_exc()
    print 'traceback.format_exc():\n%s' % traceback.format_exc()

finally:
    helper.destroy()




  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值