Skip to main content
 首页 » 编程设计

python之Python 中的游标与连接

2025年05月04日21cyq1162

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

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

请您参考如下方法:

在pyodbc中,connection.execute只是为了方便创建游标和执行cursor.execute。这包含在文档中:

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

execute()

This function is not part of the Python DB API.

Creates a new Cursor object, calls its execute method, and returns the new cursor.

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

See Cursor.execute() for more details. This is a convenience method that is not part of the DB API. Since a new Cursor is allocated by each call, this should not be used if more than one SQL statement needs to be executed on the connection.

如有疑问,只需使用Cursor.execute。