1、pymssql安装(Linux)
下载pymsql:https://pypi.python.org/pypi/pymssql
注意:先切换root权限:
sudo su -
sudo apt-get install freetds-dev
cd /home/pi/pymssql
tar zxvf pymssql-2.1.3.tar.gz
cd /home/pi/pymssql/pymssql-2.1.3
python3 setup.py install
注意: 如果安装Python2.x环境下的pymssql 需要再前置安装
sudo apt-get install python-dev
然后运行 python setup.py install
2、pymssql安装(windows)
先下载pymssql模块:http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql%20
打开cmd命令行运行
pip install C:\pymssql-2.1.3-cp35-cp35m-win_amd64.whl
3、pymssql调用方法类
1 #coding=utf-8 #!/usr/bin/env python
2
3 import pymssql
4
5 class MSSQL:
6 def __init__(self):
7 self.host = ''
8 self.user = ''
9 self.pwd = ''
10 self.db = ''
11
12 def __GetConnect(self):
13 """
14 得到连接信息
15 返回: conn.cursor()
16 """
17 if not self.db:
18 raise(NameError,"没有设置数据库信息")
19 self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,timeout=5,login_timeout=2,charset="utf8")
20 cur = self.conn.cursor()
21 if not cur:
22 raise(NameError,"连接数据库失败")
23 else:
24 return cur
25
26 ##验证数据库连接
27 def VerifyConnection(self):
28 try:
29 if self.host=='':
30 return False
31 conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,timeout=1,login_timeout=1,charset="utf8")
32 return True
33 except:
34 return False
35
36 def ExecQuery(self,sql):
37 """
38 执行查询语句
39 返回的是一个包含tuple的list,list的元素是记录行,tuple的元素是每行记录的字段
40
41 调用示例:
42 ms = MSSQL(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics")
43 resList = ms.ExecQuery("SELECT id,NickName FROM WeiBoUser")
44 for (id,NickName) in resList:
45 print str(id),NickName
46 """
47 try:
48 cur = self.__GetConnect()
49 cur.execute(sql)
50 resList = cur.fetchall()
51 #查询完毕后必须关闭连接
52 self.conn.close()
53 return resList
54 except:
55 return 'error'
56
57 def ExecNonQuery(self,sql):
58 """
59 执行非查询语句
60 调用示例:
61 cur = self.__GetConnect()
62 cur.execute(sql)
63 self.conn.commit()
64 self.conn.close()
65 """
66 cur = self.__GetConnect()
67 cur.execute(sql)
68 self.conn.commit()
69 self.conn.close()
70
71 def ExecStoreProduce(self,sql):
72 """
73 执行查询语句
74 返回的是一个包含tuple的list,list的元素是记录行,tuple的元素是每行记录的字段
75
76 调用示例:
77 ms = MSSQL(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics")
78 resList = ms.ExecQuery("SELECT id,NickName FROM WeiBoUser")
79 for (id,NickName) in resList:
80 print str(id),NickName
81 """
82 cur = self.__GetConnect()
83 cur.execute(sql)
84 resList = cur.fetchall()
85 self.conn.commit()
86 #查询完毕后必须关闭连接
87 self.conn.close()
88 return resList
89
90 def insert_Pic(self,sql,arg):
91
92 # 保存照片
93 cur = self.__GetConnect()
94 cur.execute(sql,arg)
95 self.conn.commit()
96 self.conn.close()