Python中的游标与连接

hk8txs48  于 2023-05-19  发布在  Python
关注(0)|答案(1)|浏览(163)

在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')),... ]

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

2izufjch

2izufjch1#

在pyodbc中,connection.execute仅仅是创建游标和执行cursor.execute的一种方便。以下文档中对此进行了介绍:
https://github.com/mkleehammer/pyodbc/wiki/Connection#execute

**execute()

此函数不是Python DB API的一部分。
创建一个新的Cursor对象,调用其execute方法,并返回新游标。
num_products = cnxn.execute("SELECT COUNT(*) FROM product")
更多详细信息请参见Cursor.execute()。这是一个方便的方法,不是DB API的一部分。由于每次调用都会分配一个新的Cursor,因此如果需要在连接上执行多个SQL语句,则不应使用此选项。
如果有疑问,请使用Cursor.execute

相关问题