1

我正在尝试使用 Python 并pyodbc访问 SQL Server 2008。第一个连接有效。然后,在程序完成其工作后,它会关闭连接。当程序尝试访问数据库并再次连接到它时,它在语句中失败:

self.conn = pyodbc.connect(DRIVER=self.DRIVER, SERVER=self.SERVER, DATABASE=self.DATABASE, UID=self.UID, PWD=self.PWD, charset="UTF-8")

但第一次还可以。那么有人知道为什么吗?下面是 Python 代码:

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 to the 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 for example"

    ret = ms.ExecNoQuery(conn, cursor,sql) #sql operation


    ms._UnConnect(conn, cursor) #close db


    #access the database the second time.
    ms = ODBC_MS('{SQL SERVER}', r'<server>', '<db>', '<user>',  '<password>') 
    cursor, conn = ms._GetConnect() # not success, I don't know why

    sql = "create table XX for example"
    ret = ms.ExecNoQuery(conn, cursor,sql) #sql operation

    ms._UnConnect(conn, cursor) #close db

程序第二次调用 时ms.GetConnect(),语句self.conn = pyodbc.connect(DRIVER=self.DRIVER, SERVER=self.SERVER, DATABASE=self.DATABASE, UID=self.UID, PWD=self.PWD, charset="UTF-8")失败。

4

0 回答 0