2012-02-20 85 views
1

我寫了下面的類爲我使生活更輕鬆:數據庫連接包裝

import pymssql 

class DatabaseConnection: 
    def __init__(self): 
     self.connection = pymssql.connect(host='...', user='...', password='...', database='...', as_dict=True) 

    def select(self, statement, arguments={}): 
     cur = self.connection.cursor() 
     cur.execute(statement, arguments) 
     return list(cur) 

    def __enter__(self): 
     return self 

    def __exit__(self, type, value, traceback): 
     if self.connection: 
      self.connection.close() 

我用這樣的:

<script language = "Python" runat="server"> 
    # get all that data we need to present on this asp page 
    with database.DatabaseConnection() as connection: 
     orders = connection.select('select * from ordersview') 
     special_orders = connection.select('select * from ordersview where paymenttype = %(paymentType)s', {'paymentType': 'Card'}) 
</script> 

<script language = "Python" runat="server"> 
    # later on lets use that data 
    for row in special_orders: 
     ... 
</script> 

我打算在具有連接主機類後管理我想連接的數據庫主機,但現在我硬編碼這一點。

我在這裏做過什麼不推薦或不安全的事嗎?這是一個合理的設計?是否可以返回列表(cur),因爲迭代器將超出範圍,否則在範圍之外?

感謝您的幫助,

巴里

回答

1

我想你最好使用靜態database.DatabaseConnection.getInstance(),而不是新對象的custruction。這在未來會更加靈活。您將能夠將此靜態方法用作工廠,單例或連接池管理器,以滿足您的需求。