数据库连接包装器

时间:2012-02-20 20:18:55

标签: python

我写了以下课程,让我的生活更轻松:

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 个答案:

答案 0 :(得分:1)

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