1 #!/usr/bin/env python2 #-*-coding:utf-8-*-3 4 5 ImportPyodbc6 7 8 classMSSQL:9 """Ten Package Pyodbc One """ A - def __init__(self,host,user,pwd,db='Master', charset='UTF8'): -Self._host =Host theSelf._user =User -Self._pwd =pwd -self._db =DB -Self._charset =CharSet + - def __get_connect(self): + """ A Get connection Information at return: Conn.cursor () - """ - if notself._db: - Raise(Nameerror,"database information not set") -Conn_info ='driver={sql Server};D atabase=%s; server=%s; uid=%s; pwd=%s'%(self._db, Self._host, Self._user, self._pwd) -Self.conn = Pyodbc.connect (Conn_info, charset=self._charset) inCur =self.conn.cursor () - if notcur: to Raise(Nameerror,"failed to connect to database") + Else: - returncur the * def __exec_query(self,sql): $ """Panax Notoginseng Execute Query Statement - The element that returns a list,list containing a tuple is a record row, and the elements of a tuple are the fields of each row of records the + Invocation Example: A ms = MSSQL (host= "localhost", user= "sa", pwd= "123456", db= "Pythonweibostatistics") the reslist = Ms. ExecQuery ("Select Id,nickname from Weibouser") + For (Id,nickname) in reslist: - print str (ID), nickname $ """ $cur = self.__get_connect() - cur.execute (SQL) -Reslist =Cur.fetchall () the - #connection must be closed after query is completeWuyi self.conn.close () the returnreslist - Wu defexec_query_tuple (Self, SQL): - """result set returned in tuples""" About returnSelf.__exec_query(SQL) $ - defexec_query_dict (Self, SQL): -result = [] - forRowinchSelf.__exec_query(SQL): AResult.append (Dict ([(Desc[0], Row[index]) forIndex, DESCinchEnumerate (row.cursor_description)]) ) + the returnresult - $ defexec_nonquery (self,sql): the """ the executing non-query statements the the Invocation Example: - cur = self.__getconnect () in cur.execute (SQL) the Self.conn.commit () the self.conn.close () About """ thecur = self.__get_connect() the cur.execute (SQL) the Self.conn.commit () + self.conn.close () - the Bayi if __name__=='__main__': theconn = MSSQL ('192.168.1.124','SA','hinac0m','Hinamiis','GBK') the - PrintConn.exec_query_dict ("SELECT * from Risdevice where deviceid=1")
Python accesses MS SQL Server (via PYODBC)