python - pyodbc connect to database twice and failed -
i'm trying use python , pyodbc
access sql server 2008. first connection works. then, after program finishes job, closes connection. when program tries access database , connect again, fails in statement:
self.conn = pyodbc.connect(driver=self.driver, server=self.server, database=self.database, uid=self.uid, pwd=self.pwd, charset="utf-8")
but first time ok. know why? below python code:
class odbc_ms: def __init__(self, driver,server, database, uid, pwd): ''' initialization ''' self.driver = driver self.server = server self.database = database self.uid = uid self.pwd = pwd def _getconnect(self): ''' connect db ''' if not self.database: raise(nameerror,"no getting db name") try: self.conn = pyodbc.connect(driver=self.driver, server=self.server, database=self.database, uid=self.uid, pwd=self.pwd, charset="utf-8") except exception,e: print e.message else: self.cur = self.conn.cursor() if not self.cur: raise(nameerror,"connected failed!") else: return self.cur, self.conn def execnoquery(self,conn, cursor, sql): cursor.execute(sql) ret = conn.commit() return ret def _unconnect(self,conn, cursor): conn.close() if __name__ == '__main__': ms = odbc_ms('{sql server}', r'<server>', '<db>', '<user>', '<password>') cursor, conn = ms._getconnect() #connection sql = "create table xx example" ret = ms.execnoquery(conn, cursor,sql) #sql operation ms._unconnect(conn, cursor) #close db #access database second time. ms = odbc_ms('{sql server}', r'<server>', '<db>', '<user>', '<password>') cursor, conn = ms._getconnect() # not success, don't know why sql = "create table xx example" ret = ms.execnoquery(conn, cursor,sql) #sql operation ms._unconnect(conn, cursor) #close db
the second time when program calls ms.getconnect()
, statement self.conn = pyodbc.connect(driver=self.driver, server=self.server, database=self.database, uid=self.uid, pwd=self.pwd, charset="utf-8")
fails.
Comments
Post a Comment