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),因爲迭代器將超出範圍,否則在範圍之外?
感謝您的幫助,
巴里