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'))

你可能感兴趣的:(python人工智能)