光标与Python中的连接

时间:2017-09-16 11:27:42

标签: python python-3.x cursor oledbconnection

哪一个在Python中比其他人更有效。我的要求是在关闭应用程序之前建立一个连接。

我有两个类,一个是制作和获取连接/光标,使用它我可以获取并获取我的服务中的数据。在python中跟随MVC:)

一个DBConnection类

import pyodbc

class Connection:
    def getconnection(self):
        conn =  pyodbc.connect('Driver={SQL Server};Server=.\SQLEXPRESS;Database=School;Trusted_Connection=yes;')
        print("Connection Established")
        #cursor = conn.cursor()
        return conn

    def getcursor(self):
        conn = pyodbc.connect('Driver={SQL Server};Server=.\SQLEXPRESS;Database=School;Trusted_Connection=yes;')
        print("Connection Established")
        cursor = conn.cursor()
        return cursor

和一个服务类

import Connection
import pyodbc

class StudentDataService:

    connection = Connection.Connection().getconnection()
    cursor = Connection.Connection().getcursor()

    def getstudentdata(self):
        print("In method getStudentdata()")
        try:
            row = self.connection.execute('select * from StudentGrade')
            studentList = list(row)
            return studentList
        except pyodbc.DatabaseError as err:
            print("Error Occurred while fetching Student Records", err)
            return None
        finally:
            self.connection.close()

    def getcursorstudentdata(self):
        print("In method getcursorstudentdata()")
        try:
            row = self.cursor.execute('select * from StudentGrade')
            studentList = list(row)
            return studentList
        except pyodbc.DatabaseError as err:
            print("Error Occurred while fetching Student Records", err)
            return None
        finally:
            self.cursor.close()


stu = StudentDataService()
print(stu.getstudentdata())
print("++++++++++++++++++++++++++++++++")
print(stu.getcursorstudentdata())

两者都给我结果

Connection Established
Connection Established
In method getStudentdata()
[(1, 2021, 2, Decimal('4.00')), (2, 2030, 2, Decimal('3.50')),... ]
++++++++++++++++++++++++++++++++
In method getcursorstudentdata()
[(1, 2021, 2, Decimal('4.00')), (2, 2030, 2, Decimal('3.50')),... ]

所以我的困惑是,使用哪一个?

1 个答案:

答案 0 :(得分:5)

在pyodbc中,connection.execute只是创建游标和执行cursor.execute的便利。这将在以下文档中介绍:

https://github.com/mkleehammer/pyodbc/wiki/Connection#execute

  

<强>执行()

     

此功能不是Python DB API的一部分。

     

创建一个新的Cursor对象,调用其execute方法,然后返回   新光标。

     

num_products = cnxn.execute("SELECT COUNT(*) FROM product")

     

有关详细信息,请参阅Cursor.execute()。这是一种方便的方法   这不是DB API的一部分。由于分配了新的Cursor   每次调用时,如果有多个SQL语句,则不应使用此调用   需要在连接上执行。

如果有疑问,请使用Cursor.execute