52
loading...
This website collects cookies to deliver better user experience
Python file | Functionality |
---|---|
migrate_manager.py | Migration manager |
base.py | Model manager |
db_manager.py | Database manager |
example.db
”, then make a cursor to execute SQL commands without forgetting to commit the changes and to close the connection.import sqlite3
con = sqlite3.connect('example.db')
cursor= con.cursor()
cursor.execute('''CREATE TABLE stocks (date text, trans text, symbol text, qty real, price real)''')
cursor.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
connection.commit()
connection.close()
ConnectionSqliteManager
that opens an SQL connection and instantiates the cursor object.__enter__
and __exit__
magic class methods as a necessary ingredient for database resource management.__enter__
method connects the example.db
file (setup operation) and returns the Connection object to variable Connection.__exit__
method takes care of closing the connection on exiting the with block(teardown operation).with
, you manage database within the scope, without taking the bother of opening and closing the connection.class ConnectionSqliteManager:
def __init__(self,filename):
self.filename = filename
def __enter__(self):
print("Connection started ...")
self.connection = sql3.connect(self.filename)
self.cursor = self.connection.cursor()
return self
def __exit__(self, type, value, traceback):
print("Connection ended ...")
self.connection.close()
with ConnectionSqliteManager("example.db") as Connection:
# Do what you want with Connection instance
#inside ConnectionSqliteManager class
def commit(operation):
def wrapper(self, *args,**kwargs):
operation(self, *args, **kwargs)
self.connection.commit()
return wrapper
@commit
def Sql_operation(self):
# execute an sql command here
pass
class Model(baseModel):
base_model = base
tablename = "Model"
fields = ("field_1", "field_2")
model_list
list:model_list = [Model,
]
argparse
default library to let the user input the arguments in the command prompt and execute the migration.migrate_manager.py
file, there is no need to explain each line of code. I made it as simple as possible.python migrate_manager.py migrate
Begin database Migration ...
Model Migration
Connection started ...
Model: created successfully!
2022-01-04 02:29:53.402991: Commit is successful!!
Connection ended ...