简体   繁体   English

如何返回sqlite3数据库访问响应

[英]How to return sqlite3 db access responses

I'm new to Python. 我是Python的新手。 I've just created a sqlite3 db wrapper class to handle the database interaction in my application. 我刚刚创建了一个sqlite3 db wrapper类来处理应用程序中的数据库交互。 My question is how do I return success/failure messages from my db wrapper class methods, addRow, updRow (which add and update rows) to the invoking program? 我的问题是如何从数据库包装器类方法addRow,updRow(添加和更新行)返回成功/失败消息到调用程序?

Here's the class code I cobbled together so far:- 到目前为止,这是我拼凑的课程代码:-

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()

I think there are 2 ways you can do this. 我认为有两种方法可以做到这一点。 You can: 您可以:

  1. Change the return type of you function to something like a tuple of (error_code, SQL_results), or 将函数的返回类型更改为类似的元组(error_code,SQL_results),或
  2. Throw an exception if the query fails (or don't catch the one you already are handling) and leave the exception handling logic to the user (calling program). 如果查询失败(或不捕获您已经在处理的查询),则引发异常,并将异常处理逻辑留给用户(调用程序)。

I think option 2 is the better way. 我认为选项2是更好的方法。

Also, I think your query building would be more clear (or at least more concise) using something like the following (assumes that data is a dictionary) 另外,我认为您的查询构建将使用以下类似内容(假设数据是字典)将更加清晰(或至少更加简洁)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM