2017-09-16 69 views
1

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

所以我的困惑是,這一個使用?

回答

3

在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