Как обработка ошибок работает с sqlite3 python - PullRequest
0 голосов
/ 04 апреля 2019

Я создаю оболочку класса для базы данных sqlite в python, и я хотел бы знать, как я должен делать правильную обработку ошибок для баз данных в целом в python.Приведенный ниже код показывает простое открытие и закрытие соединений и курсоров, а также выполнение и принятие транзакций.

В общем, я хотел бы выяснить, следует ли помещать каждую функцию в отдельный блок try-Кроме или помещать ихвместе в одно.Я надеюсь, что это также может помочь другим, кто любит сосредоточиться на обработке ошибок.

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