Python中的光标Vs连接
问题描述:
在Python中,哪一种效率比其他效率更高。我的要求是有一个连接,直到我们关闭应用程序。Python中的光标Vs连接
我有两个类,一个是让连接/光标,并使用我能够获取和获取我的服务中的数据。在python :)
一个DBConnection的类继MVC
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
执行()
此函数不是Python的DB API的一部分。
创建一个新的
Cursor
对象,调用它的execute方法并返回 新游标。
num_products = cnxn.execute("SELECT COUNT(*) FROM product")
详情请参阅
Cursor.execute()
。这是一种方便的方法 ,它不是DB API的一部分。由于每个调用都会分配一个新的Cursor
,因此如果需要在连接上执行多个SQL语句 ,则不应使用这个值。
如果有疑问,只需使用Cursor.execute
。