Python 想要和MSSql数据库进行交互,首先要下载名为"pymssql"的包,然后import该包
Python实现连接mssql数据库,并做简单的操作:查询和非查询操作,代码如下:
#!usr/bin/python
# -*- coding:utf-8 -*-
import pymssql
class MSSQL:
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,"no ")
# 打开数据库连接
self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8")
# 使用cursor()方法获取操作游标
cur = self.conn.cursor()
if not cur:
raise(NameError,"connect database fails")
else:
return cur
def ExecQuery(self,sql):
try:
cur = self.__GetConnect()
# 执行SQL语句