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),因为迭代器将超出范围,否则在范围之外?
感谢您的帮助,
巴里