Python连接SQL Server数据获取2

python学习网 2017-12-22 17:08:01
# -*- coding:utf-8 -*-

import pymssql
import json

class MSSQLTABEL:
    def __init__(self,host,user,pwd,db):
        self.host = host
        self.user = user
        self.pwd = pwd
        self.db = db

    def __GetConnect(self):
        if not self.db:
            raise(NameError,"连接数据库了吗?")
        self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8")
        cursor = self.conn.cursor()
        if not cursor:
            raise(NameError,"连接数据库失败")
        else:
            return cursor

    def ExecQuery(self,sql):
        cursor = self.__GetConnect()
        cursor.execute(sql)
        resList = cursor.fetchall()

        #查询完毕后必须关闭连接
        self.conn.close()
        return resList

    def ExecNonQuery(self,sql):
        cursor = self.__GetConnect()
        cursor.execute(sql)
        self.conn.commit()
        self.conn.close()

msList = MSSQLTABEL(host="1.1.1.1",user="1",pwd="123",db="test_1")
reslist = msList.ExecQuery("select * from A2017")
for i in reslist:
    print json.dumps(i,ensure_ascii=False)

 

阅读(783) 评论(0)