如何返回sqlite3 db访问响应

2024-10-01 04:58:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python还不熟悉。我刚刚创建了一个sqlite3db包装类来处理应用程序中的数据库交互。我的问题是如何将db包装类方法addRow、updRow(添加和更新行)中的成功/失败消息返回给调用程序?你知道吗

这是我拼凑的类码远:-你知道吗

class dbManager(object):
    def __init__(self, db):
        self.conn = lite.connect(db)
        self.conn.execute('pragma foreign_keys = on')
        self.conn.execute('pragma synchronous=off')
        self.conn.commit()
        self.cur = self.conn.cursor()

    def query(self, arg):
        self.cur.execute(arg) 
        self.conn.commit()
        return self.cur

    def addRow(self, tablename, data):
        """
        Insert data into a table. The data does not have to be escaped.
        """
        global actInserts

        # Create a new cursor
        # tc = self.conn.cursor() # opened at init 

        tablelist = ""
        valueholder = ""
        valuelist = []

        for key, value in data.items():
            if len(tablelist) > 0:
                tablelist += ', '
                valueholder += ', '

            # Add to table column list
            tablelist += key

            # Add a holder
            valueholder += '?'

            # build the insert values 
            valuelist.append(value)

        # Perform and commit the insert       
        try:
            dbResponse = self.cur.execute("INSERT INTO " + tablename + " (" + tablelist + ") VALUES (" + valueholder + ");", valuelist)
            actInserts += 1
        except lite.Error, e:
            dbResponse = 'Sqlite Error NP: ' + e.args[0] 
            print 'Sqlite Error NP: ' + e.args[0] 
        return dbResponse

    def closeConnection (self):
        self.conn.commit()
        self.conn.close() 

    def __del__(self):
        self.conn.close()

Tags: selfexecutedbdatadeferrorconncursor
1条回答
网友
1楼 · 发布于 2024-10-01 04:58:51

我认为有两种方法可以做到这一点。您可以:

  1. 将函数的返回类型更改为元组(error\u code,SQL\u results),或
  2. 如果查询失败(或者没有捕获到您正在处理的异常),则抛出异常,并将异常处理逻辑留给用户(调用程序)。你知道吗

我认为选择2是更好的方法。你知道吗

另外,我认为您的查询构建将更清晰(或者至少更简洁)使用如下内容(假设数据是字典)

tablelist = ','.join(list(data.viewkeys()))
valueholder = ','.join(['?' for i in data.viewkeys()])
valuelist = list(data.viewvalues())

相关问题 更多 >