本文記錄python 中sql server 的封裝及使用。
1 先封裝鏈接數據庫所需要的信息
#coding=gbk
class Configration:
"""description of class"""
host="JINJIEGO\SQLEXPRESS"
port=1433
user="sa"
pwd="123456"
db="test"
def __init__(self):
pass
2 爲了避免程序中頻繁鏈接數據庫導致的資源消耗,可以創建一個全局對象,一直保持與數據庫的鏈接,將此過程封裝起來
#coding=gbk
import sys
import pymssql
from Configration import Configration
class UniqueObject(Configration): #only offer a support of connecting db
"""description of class"""
cur=None
conn=None
def __init__(self):
Configration.__init__(self)
def __del__(self):
if self.conn!=None:
self.conn.close()
print(">>>>>>>>>>>>>>>>>Connection has been closed!<<<<<<<<<<<<<<<<<<<")
@staticmethod
def GetObject():
if UniqueObject.cur==None:
print(">>>>>>>>>>>>>>>>>Connecting to Database.....<<<<<<<<<<<<<<<<<<")
return UniqueObject.__GetConnect()
return UniqueObject.conn,UniqueObject.cur
def __GetConnect():
if not Configration.db: raise(NameError,"no db Info")
UniqueObject.conn =pymssql.connect(host=Configration.host,port=Configration.port,\
user=Configration.user,password=Configration.pwd,\
database=Configration.db,charset="utf8")
UniqueObject.cur=UniqueObject.conn.cursor()
if not UniqueObject.cur: raise(NameError,"Connection error!")
else: return UniqueObject.conn,UniqueObject.cur
3 封裝查詢功能,主要是ExecQuery和ExecNonQuery
#coding=gbk
import pymssql
import sys
sys.path.append(".")
from Configration import *
from UniqueObject import UniqueObject
class MSSQL(object):
conn,cur=UniqueObject.GetObject()
def __init__(self):
pass
def __del__(self):
#print("\n MSSQL object has been realsed!")
pass
def ExecQuery(self,sql):
MSSQL.cur.execute(sql)
reslist=self.cur.fetchall()
return reslist
def ExecNonQuery(self,sql):
#try:
MSSQL.cur.execute(sql)
MSSQL.conn.commit()
#except:
#print("\nInserting exception!")
使用時,類A的相關操作可以繼承MSSQL,然後在A裏面寫相應的增刪改查操作。