1.目标数据sql2008 R2 ComPrject=>TestModel
2.安装python 连接mssql 模块
运行 pip install pymssql-2.2.0.dev0-cp36-cp36m-win_amd64.whl
运行完毕 查看是否成功 pip -m list
3.编写python 代码
1 import time 2 import pymssql 3 #import decimal 4 5 class MSSQL: 6 def __init__(self,host,user,pwd,db): 7 self.host=host 8 self.user=user 9 self.pwd=pwd 10 self.db=db 11 def GetConnect(self): 12 if not self.db: 13 raise(NameError,'没有目标数据库') 14 self.connect=pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset='utf8') 15 cur=self.connect.cursor() 16 if not cur: 17 raise(NameError,'数据库访问失败') 18 else: 19 return cur 20 def ExecSql(self,sql): 21 cur=self.GetConnect() 22 cur.execute(sql) 23 self.connect.commit() 24 self.connect.close() 25 def ExecQuery(self,sql): 26 cur=self.GetConnect() 27 cur.execute(sql) 28 resList = cur.fetchall() 29 self.connect.close() 30 return resList 31 def main(): 32 ms = MSSQL(host="192.168.0.108", user="sa", pwd="sa", db="ComPrject") 33 resList = ms.ExecQuery("select *from TestModel") 34 print(resList) 35 36 if __name__ == '__main__': 37 main() 38 input("执行完成:")
4.运行效果
备注:如果读取中文出现乱码,需要修改varchar=>nvarchar