【问题标题】:Database connection wrapper数据库连接包装器
【发布时间】: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


    【解决方案1】:

    我认为您最好使用静态 database.DatabaseConnection.getInstance() 而不是 custruction 新对象。这将在未来更加灵活。您将能够将此静态方法用作满足您需求的工厂、单例或连接池管理器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-13
      • 1970-01-01
      • 1970-01-01
      • 2021-09-15
      • 2017-03-07
      相关资源
      最近更新 更多