一、ORM基本介紹 ORM 是 python編程語言後端web框架 Django的核心思想,“Object Relational Mapping”,即對象-關係映射,簡稱ORM。 二、實現目標 創建一個實例對象,用創建它的類名當做數據表名,用創建它的類屬性對應數據表的欄位,當對這個實例對象操作時,能 ...
一、ORM基本介紹
ORM 是 python編程語言後端web框架 Django的核心思想,“Object Relational Mapping”,即對象-關係映射,簡稱ORM。
二、實現目標
創建一個實例對象,用創建它的類名當做數據表名,用創建它的類屬性對應數據表的欄位,當對這個實例對象操作時,能夠對應MySQL語句
如圖:
三、代碼實現
class ModelMetaClass(type):
def __new__(cls, name, bases, attrs):
mappings = dict()
for k, v in attrs.items():
# 只處理類中屬性值為元組的鍵值對
if isinstance(v, tuple):
mappings[k] = v
# 處理完成後刪除屬性
for k in mappings:
attrs.pop(k)
attrs["__mappings__"] = mappings
attrs["__table__"] = name
# 這裡不能用type(name, bases, attrs) 直接返回創建好的類, 不會觸發type的__init__方法
return type.__new__(cls, name, bases, attrs)
class Model(metaclass=ModelMetaClass):
# uid = ("uid", "int unsigned")
# name = ("username", "varchar(30)")
# email = ("email", "varchar(30)")
# password = ("password", "varchar(30)")
def __init__(self, **kwargs):
# 將關鍵字參數添加到實例屬性
for k, v in kwargs.items():
setattr(self, k, v)
def save(self):
table_name = self.__table__
field = list()
args = list()
for k, v in self.__mappings__.items():
field.append(v[0])
arg = getattr(self, k, None)
# ["12345","""'Michael'""","""'[email protected]'""","""'my-pwd'"""]
if isinstance(arg, str):
args.append("""'{}'""".format(arg))
else:
args.append(str(arg))
sql = "insert into {}({}) values ({})".format(table_name, ",".join(field), ",".join(args))
print(f"SQL語句: {sql}")
class User(Model):
uid = ("uid", "int unsigned")
name = ("username", "varchar(30)")
email = ("email", "varchar(30)")
password = ("password", "varchar(30)")
u = User(uid=12345, name="Michael", email="[email protected]", password="my-pwd")
u.save()
代碼運行結果: