|
#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()
|
|
|