Python指Dao一下

将两个字典合并为一个字典:
dict_1 = {"name": "张三", "age": 25, "lessons": ["Python", "Java"]}
dict_2 = {"gender": "男", "name": "张三", "phone": 12345678999}

https://blog.csdn.net/weixin_37994148/article/details/99731818?ops_request_misc=&request_id=&biz_id=&utm_medium=distribute.pc_search_result.none-task-blog-2~all~koosearch~default-4-99731818-null-null.142^v86^koosearch_v1,239^v2^insert_chatgpt&utm_term=python%20%E5%AD%97%E5%85%B8%E5%8E%BB%E9%87%8D%E5%90%88%E5%B9%B6&spm=1018.2226.3001.4187

  • 这篇博客: Python快速进阶知识点【岗前必备技能】中的 4.3.2 DAO设计 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • 类的类型:
    - 数据类、 实体类(Entity),表示业务中与数据表对应的类。
    - 业务类、功能类(Service),对数据类进行增删改查操作。
    - 工具类,扩展功能(Utils或Helper),在处理业务时,方便调用,如md5加密、日志记录、缓存、短信验证、图片验证码、简化网络操作。
    - 数据操作类 DAO类: 只对象数据实体类,简化对象与数据库的操作。
    
    class Singleton:
        def __init__(self, cls):
            self.cls = cls
    
        def __call__(self, *args, **kwargs):
            if not hasattr(self.cls, "instance"):
                self.cls.instance = self.cls(*args, **kwargs)
    
            return self.cls.instance
    
    @Singleton
    class DB():
        def __init__(self):
            params = {
                "host": "10.12.153.232",
                "port": 3307,
                "user": "root",
                "passwd": "root",
                "charset": "utf8",
                "db": "stu",
                "cursorclass": pymysql.cursors.DictCursor  
            }
            self.conn = pymysql.Connect(**params)
    
        def __enter__(self):
            return self.conn.__enter__()
    
        def __exit__(self, exc_type, exc_val, exc_tb):
            return self.conn.__exit__(exc_type, exc_val, exc_tb)
    
        def __del__(self):
            self.conn.close()
    

    DictCursor字典游标类,查询结果自动转化列表+字典的结构,这样的结果便于json序列化。

    class BaseDao():
        def __init__(self, table_name=None, pk_name="id"):
            self.table = table_name  # 当前Dao操作的表名称
            self.pk = pk_name  # 当前Dao操作的表的主键名
    
            self.db = DB()
    
        def get_table(self, obj=None):
            if self.table is None:
                self.table = obj.__class__.__name__.lower()
    
            return self.table
    
        def save(self, t):
            # sql = "insert into teacher(tn, name) values( %(tn)s, %(name)s )"
            sql = "INSERT INTO %s(%s) VALUES (%s)"
    
            table = self.get_table(t)
    
            colums = ",".join(t.__dict__)
            colums_placeholds = ",".join(["%%(%s)s" % name for name in t.__dict__])
    
            with self.db as c:
                c.execute(sql % (table, colums, colums_placeholds), t.__dict__)
                self.msg("Add", c.rowcount)
    
        def update(self, t):
            # update student set name=%(name)s,age=%(age)s,sex=%(sex)s where sn="08"
            sql = "UPDATE %s SET %s WHERE %s"
            obj_dict = t.__dict__
    
            # 获取主键值
            pk = obj_dict.pop(self.pk)  # 弹出主键列和它的值, 避免set 语句中出现主键值更新
    
            update_cols = ",".join("%s=%%(%s)s" % (col_name, col_name) for col_name in obj_dict)
            where_str = f"{self.pk}={pk}"
    
            with self.db as c:
                c.execute(sql % (self.get_table(), update_cols, where_str), obj_dict)
                self.msg("Update", c.rowcount)
    
        def remove(self, pk):
            sql = f"delete from {self.get_table()} where {self.pk}={pk}"
            with self.db as c:
                c.execute(sql)
                self.msg("Delete", c.rowcount)
    
        def remove_batch(self, *pks):
            with self.db as c:
                for pk in pks:
                    sql = f"delete from {self.get_table()} where {self.pk}={pk}"
                    c.execute(sql)
                self.msg("Delete", c.rowcount)
    
        def get(self, cls, pk):
            # select * from student where sn=%s
            sql = "SELECT * FROM %s WHERE %s"
            with self.db as c:
                c.execute(sql % (self.table, f"{self.pk}={pk}"))
                ret = c.fetchone()
    
            return cls(**ret)
    
        def list(self, cls):
            sql = f"select * from {self.get_table()}"
            with self.db as c:
                c.execute(sql)
                ret = c.fetchall()
    
            # 将[{}] 转成 [<对象>]
            return [cls(**dict_obj) for dict_obj in ret]
    
        def msg(self, title, rowcount):
            if rowcount > 0:
                print(f"{title} OK")
            else:
                print(f"{title} Error")
    
    class TeacherDao(BaseDao):
        def __init__(self):
            super(TeacherDao, self).__init__("teacher", "tn")
    
        def save(self, t):
            super(TeacherDao, self).save(t)
    
        def update(self, t):
            super(TeacherDao, self).update(t)
    
        def remove(self, pk):
            super(TeacherDao, self).remove(pk)
    
        def get(self,pk):
            return super(TeacherDao, self).get(Teacher, pk)
    
        def list(self):
            return super(TeacherDao, self).list(Teacher)
    
        def remove_batch(self, *pks):
            super(TeacherDao, self).remove_batch(*pks)
    
    
    if __name__ == "__main__":
        dao = TeacherDao()
    
        # t1 = Teacher("08", "Disen")
        # dao.save(t1)
        #
        # t2 = dao.get("08")
        # t2.name = "狄老师"
        # dao.update(t2)
        #
        # print(dao.get("08"))
        # dao.remove("08")
    
        dao.remove_batch("04", "05", "06")
        print(dao.list())
    
  • 以下回答由chatgpt基于相关博客总结生成:

    可以使用Python内置的.update()方法将两个字典合并为一个字典:

    dict1 = { 'a':1, 'b':2 }
    dict2 = { 'c':3, 'd':4 }
    result = dict1.copy() # 先拷贝一个字典,避免修改原始字典
    result.update(dict2) # 使用.update()方法将字典合并
    print(result) # 输出{'a':1, 'b':2, 'c':3, 'd':4}
    

    这里我们先拷贝一个字典,避免直接修改原始字典。然后使用.update()方法将另一个字典合并进去,最后输出合并后的字典。

    如果你想将多个字典合并,可以考虑使用循环进行:

    dict1 = { 'a':1, 'b':2 }
    dict2 = { 'c':3, 'd':4 }
    dict3 = { 'e':5, 'f':6 }
    result = dict1.copy()
    for d in [dict2, dict3]:
        result.update(d)
    print(result) # 输出{'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6}
    

    这里使用一个列表包含需要合并的字典,然后使用循环来逐一合并,最终得到一个合并后的字典。