1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
| #coding=utf-8
#!/usr/bin/env python
import pymssql
import ConfigParser
class MSSQL:
def __init__(self):
cf = ConfigParser.ConfigParser()
cf.read("mssql.conf")
self.host = cf.get("DB","host")
self.user = cf.get("DB","user")
self.pwd = cf.get("DB","pwd")
self.db = cf.get("DB","db")
def __GetConnect(self):
"""
get connetion info
response: conn.cursor()
"""
#if not self.db:
# raise(NameError,"no db conf file found")
self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,timeout=5,login_timeout=2,charset="utf8")
cur = self.conn.cursor()
if not cur:
raise(NameError,"fail connecting to DB")
else:
return cur
##verify DB connection
def VerifyConnection(self):
try:
if self.host=='':
return False
conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,timeout=1,login_timeout=1,charset="utf8")
return True
except:
return False
def ExecQuery(self,sql):
"""
execute query
get a list including tuple, elements of list are row of record, elements of tuple is fields
demo
ms = MSSQL(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics")
resList = ms.ExecQuery("SELECT id,NickName FROM WeiBoUser")
for (id,NickName) in resList:
print str(id),NickName
"""
cur = self.__GetConnect()
cur.execute(sql)
resList = cur.fetchall()
#resList = cur.description
#close connection after querying
self.conn.close()
return resList
def ExecNonQuery(self,sql):
"""
execute no query
demo
cur = self.__GetConnect()
cur.execute(sql)
self.conn.commit()
self.conn.close()
"""
cur = self.__GetConnect()
cur.execute(sql)
self.conn.commit()
self.conn.close()
def ExecStoreProduce(self,sql):
"""
execute query
get a list including tuple, elements of list are row of record, elements of tuple is fields
demo:
ms = MSSQL(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics")
resList = ms.ExecQuery("SELECT id,NickName FROM WeiBoUser")
for (id,NickName) in resList:
print str(id),NickName
"""
cur = self.__GetConnect()
cur.execute(sql)
resList = cur.fetchall()
self.conn.commit()
#close connection after querying
self.conn.close()
return resList
def main():
sqlquery="select * from MyDB..MyTable"
sqlconn=MSSQL()
res=sqlconn.ExecQuery(sqlquery)
for data in res:
print data
if __name__=='__main__':
main()
|