2017-09-16 9 views
1

Pythonで他のものより効率的です。私の要件は、アプリケーションを閉じるまで1つの接続を持つことです。Pythonでのカーソル対接続

私は2つのクラスを作成し、接続/カーソルを取得して、私が取得して、私のサービスでデータを取得できるようにしています。 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 

と1サービスクラスは

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

だから私の混乱は、ある結果私に与えています1つを使用する?

答えて

3

pyodbcでは、connection.executeは、カーソルを作成してcursor.executeを実行するのに便利です。この関数は、Python DB APIの一部ではありません()

実行

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

:これはでドキュメントに覆われています。

新しいCursorオブジェクトを作成し、その実行メソッドを呼び出し、 新しいカーソルを返します。

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

詳細はCursor.execute()を参照してください。これは、DB APIの一部ではない便利なメソッド です。新しいCursorは各呼び出し によって割り当てられるため、複数のSQL文 を接続上で実行する必要がある場合は、これを使用しないでください。

疑問がある場合は、Cursor.executeを使用してください。