【发布时间】:2012-02-22 01:44:23
【问题描述】:
为了让我的生活更轻松,我编写了以下课程:
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>
我打算稍后拥有一个连接主机类来管理我希望连接的数据库主机,但现在我对此进行了硬编码。
我在这里做过什么你认为不推荐或不安全的事情吗?设计合理吗?是否可以返回 list(cur) 因为迭代器将超出范围,否则在 with 范围之外?
感谢您的帮助,
巴里
【问题讨论】:
标签: python