|
@@ -0,0 +1,60 @@
|
|
|
|
+import sqlite3
|
|
|
|
+
|
|
|
|
+def test_sqlite():
|
|
|
|
+
|
|
|
|
+ try:
|
|
|
|
+ con = sqlite3.connect("mydb.sqlite")
|
|
|
|
+ except sqlite3.Error as er:
|
|
|
|
+ print("Error connecting to database:", er)
|
|
|
|
+
|
|
|
|
+ cur = con.cursor()
|
|
|
|
+ sql_query = "INSERT INTO user VALUES(?, ?)"
|
|
|
|
+ sql_data = ("John", "MacDonald")
|
|
|
|
+
|
|
|
|
+ try:
|
|
|
|
+ cur.execute(sql_query, sql_data)
|
|
|
|
+ con.commit()
|
|
|
|
+ except sqlite3.Error as er:
|
|
|
|
+ print('SQLite error: %s' % (' '.join(er.args)))
|
|
|
|
+ print("Exception class is: ", er.__class__)
|
|
|
|
+ print('SQLite traceback: ')
|
|
|
|
+ finally:
|
|
|
|
+ con.close()
|
|
|
|
+
|
|
|
|
+class DatabaseManager:
|
|
|
|
+ def __init__(self, db_name):
|
|
|
|
+ self.db_name = db_name
|
|
|
|
+
|
|
|
|
+ def __enter__(self):
|
|
|
|
+ try:
|
|
|
|
+ self.conn = sqlite3.connect(self.db_name)
|
|
|
|
+ except sqlite3.Error as e:
|
|
|
|
+ print("Error connecting to database:", e)
|
|
|
|
+ return None
|
|
|
|
+ else:
|
|
|
|
+ return self.conn
|
|
|
|
+
|
|
|
|
+ def __exit__(self, exc_type, exc_value, traceback):
|
|
|
|
+ try:
|
|
|
|
+ self.conn.close()
|
|
|
|
+ except AttributeError:
|
|
|
|
+ print("Database connection not established")
|
|
|
|
+ except sqlite3.Error as e:
|
|
|
|
+ print("An error occured while closing the database connection: ", e)
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+def test_context():
|
|
|
|
+ with DatabaseManager("mydb.sqlite") as conn:
|
|
|
|
+ if conn:
|
|
|
|
+ cur = conn.cursor()
|
|
|
|
+ sql_query = "INSERT INTO user VALUES(?, ?)"
|
|
|
|
+ sql_data = ("Jogn", "MacDonald")
|
|
|
|
+ cur.execute(sql_query, sql_data)
|
|
|
|
+ conn.commit()
|
|
|
|
+
|
|
|
|
+def main():
|
|
|
|
+ # test_sqlite()
|
|
|
|
+ test_context()
|
|
|
|
+
|
|
|
|
+if __name__ == '__main__':
|
|
|
|
+ main()
|