import pymssql #导入sql server数据库的包
class MSSQL:
def __init__(self,host,user,pwd,db):
self.host = host
self.user = user
self.pwd = pwd
self.db = db
def __GetConnect(self):
'''
连接数据库
'''
try:
self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8")
db = self.conn.cursor()
return db
except Exception as e:
raise e
def ExecQuery(self,sql):
'''
查询数据库
'''
try:
db = self.__GetConnect()
db.execute(sql)
resList = db.fetchall()
self.conn.close()
return resList
except Exception as e:
raise e
def ExecNonQuery(self,sql):
'''
更新数据库
'''
try:
db = self.__GetConnect()
db.execute(sql)
self.conn.commit()
self.conn.close()
except Exception as e:
raise e
# #创建数据库连接对象
# ms = MSSQL(host=".",user="sa",pwd="sa",db="dvbbs8")
# # 查询数据库示例
# reslist = ms.ExecQuery("select * from users")
# list(map(print, reslist))
# # 更新数据库示例
# newsql="update users set password='pass' where id=1"
# ms.ExecNonQuery(newsql.encode('utf-8'))
【script】python使用pymssql模块访问SQL Server(Mssql)
最新推荐文章于 2022-11-01 07:24:45 发布