Python操作sqlserver数据库

1.安装epel源:
yum -y install epel-release
2.安装pip:
yum -y install python-pip
【Python操作sqlserver数据库】3.清缓存:
yum clean all
4.升级pip:
pip install --upgrade pip
5.安装pymssql:
pip install pymssql

1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 import pymssql 5 6 class MSSQL: 7def __init__(self,host,user,pwd,db): 8self.host = host 9self.user = user 10self.pwd = pwd 11self.db = db 12 13def __GetConnect(self): 14if not self.db: 15raise(NameError,"没有设置数据库信息") 16self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8") 17cur = self.conn.cursor() 18if not cur: 19raise(NameError,"连接数据库失败") 20else: 21return cur 22 23def ExecQuery(self,sql): 24cur = self.__GetConnect() 25cur.execute(sql) 26resList = cur.fetchall() 27 28#查询完毕后必须关闭连接 29self.conn.close() 30return resList 31 32def ExecNonQuery(self,sql): 33cur = self.__GetConnect() 34cur.execute(sql) 35self.conn.commit() 36self.conn.close() 37 38 ms = MSSQL(host="10.7.125.1",user="sa",pwd="test",db="test1") 39 reslist = ms.ExecQuery("select "字段" from "表名" where "条件字段"=5") 40 for i in reslist: 41print (i) 42 43 newsql="update "表名" set "字段"='%s' where "条件字段"="改前值"%u'改后值' 44 print (newsql) 45 ms.ExecNonQuery(newsql.encode('utf-8'))

    推荐阅读