Python操作sqlserver数据库

1.安装epel源:

yum -y install epel-release

2.安装pip:

yum -y install python-pip

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:
 7     def __init__(self,host,user,pwd,db):
 8         self.host = host
 9         self.user = user
10         self.pwd = pwd
11         self.db = db
12 
13     def __GetConnect(self):
14         if not self.db:
15             raise(NameError,"没有设置数据库信息")
16         self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8")
17         cur = self.conn.cursor()
18         if not cur:
19             raise(NameError,"连接数据库失败")
20         else:
21             return cur
22 
23     def ExecQuery(self,sql):
24         cur = self.__GetConnect()
25         cur.execute(sql)
26         resList = cur.fetchall()
27 
28         #查询完毕后必须关闭连接
29         self.conn.close()
30         return resList
31 
32     def ExecNonQuery(self,sql):
33         cur = self.__GetConnect()
34         cur.execute(sql)
35         self.conn.commit()
36         self.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:
41     print (i)
42 
43 newsql="update "表名" set "字段"='%s' where "条件字段"="改前值"%u'改后值'
44 print (newsql)
45 ms.ExecNonQuery(newsql.encode('utf-8'))

 

转载于:https://www.cnblogs.com/Ghost-bird/p/10494608.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值