Welche ist effizienter als andere in Python. Meine Anforderung besteht darin, eine Verbindung zu haben, bis wir die Anwendung schließen.Cursor Vs Verbindung in Python
Ich habe zwei Klassen, die man machen und Verbindung/Cursor bekommen und mit denen ich die Daten in meinem Service holen und holen kann. MVC in Python verfolgt :)
One DBConnection Klasse
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
und eine Service-Klasse
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())
Und beide geben mir Ergebnisse
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')),... ]
Also meine Verwirrung ist, die ein zu verwenden?