database class python

Solutions on MaxInterview for database class python by the best coders in the world

showing results for - "database class python"
Aurélie
04 Aug 2017
1import sqlite3
2
3class DBConnection:
4    instance = None
5
6    def __new__(cls, *args, **kwargs):
7        if cls.instance is None:
8            cls.instance = super().__new__(DBConnection)
9            return cls.instance
10        return cls.instance
11
12    def __init__(self, db_name='you-db-name'):
13        self.name = db_name
14        # connect takes url, dbname, user-id, password
15        self.conn = self.connect(db_name)
16        self.cursor = self.conn.cursor()
17
18    def connect(self):
19        try:
20            return sqlite3.connect(self.name)
21        except sqlite3.Error as e:
22            pass
23
24    def __del__(self):
25        self.cursor.close()
26        self.conn.close()
27