sqlite3 python如何进行错误处理

时间:2019-04-04 08:50:52

标签: python sqlite error-handling try-except

我在python中为sqlite数据库创建一个类包装器,我想知道我应该如何在python中为数据库做适当的错误处理。下面的代码仅显示打开和关闭连接和游标以及事务的执行和提交。

通常来说,我想确定是否应该将每个功能放入专用的try-except块中或将它们组合为一个。 我希望这也可以帮助其他喜欢专注于错误处理的人。

import sqlite3 as lite

class DB:

    """
      init the db connection when path to db is set
      this try-except block is rather simple and straight forward
    """

    def __init__(self, db_path=None):
        self.conn = None
        self.cur = None
        if db_path:
            try:
                self.conn = lite.connect(db_path)
            except lite.Error as err:
                exit(err)


    """
      When exiting, I test if the connection is set.
      Should I check if a cursor has not been closed yet
      or if a transaction has not been committed?
    """

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.conn:
            try:
                self.conn.close()
            except lite.Error as err:
                exit(err)


    """
      I just create a test table in this case and I'm completely
      unsure how to handle the try-except blocks.

      Should I put the creation of the cursor in a separate block?
      Is it sensible to put the closing function into finally or 
      should I create another block for that?
    """

    def create_table(self):
        try:
            self.cur = self.conn.cursor()
            self.cur.execute("""CREATE TABLE IF NOT EXISTS testtable 
                                    (age integer,
                                    name text NOT NULL,
                                    begin_date text,
                                    end_date text);""")
        except lite.Error as err:
            exit(err)
        finally:
            self.cur.close()


    """
      The same question arises as with the create_table function.
      I probably need to rollback here as well if an error occurs.
    """

    def insert_rows(self):
        try: 
            self.cur = self.conn.cursor()
            self.cur.execute("""INSERT INTO testtable 
                           values(23, "Max", "2019-04-04", 
                           "2019-11-23")""")
            self.conn.commit()
        except lite.Error as err:
            self.conn.rollback()
            exit(err)
        finally:
            self.cur.close()

0 个答案:

没有答案