实例化user表后调用inset()方法,报错了
实例化user表后调用inset()方法,报错提示在User类中调用父类Model的构造函数有问题:TypeError: object.__init__() takes exactly one argument (the instance to initialize)
代码如下:
import pymysql class MyORM: def __init__(self): # 建立与数据库的链接 conn = pymysql.connect( host='192.168.8.30', port=3306, user='admin1', password='123', database='shouji', charset='utf8', # pymysql.cursors.DictCursor该方法是创建列表嵌套字典的游标返回[{},{},{}] cursorclass=pymysql.cursors.DictCursor, # 第二种方式:数据提交,自动提交方式 autocommit=True ) # 实例化一个游标对象 cursor = conn.cursor() self.cursor = cursor def execute(self,sql): self.cursor.execute(sql) return self.cursor.fetchall() # 标准ORM父类,基本模型 class Model: # 这个构造方法里面的代码是给数据插入的时候用的 def __int__(self, **kwargs): for k,v in kwargs.items(): self.__setattr__(k, v) # 通过链式操作来制定查询的列,就是一顿.然后去调用各种方法 def field(self,select_params): # 把列表转成字符串 self.columns = ",".join(select_params) return self # 查询 def query(self,**where_params): # 获取子类的属性,也就是表名 table = self.__class__.__getattribute__(self,'table_name') if hasattr(self,"columns"): sql = "select %s from %s" % (self.columns,table) else: sql = "select * from %s" % (table) # 判断where_params是否有参数 if where_params is not None: sql += " where " for k, v in where_params.items(): sql += " %s='%s' and" % (k, v) sql += ' 1=1 limit 1' print(sql) return MyORM().execute(sql) def insert(self): # sql = "insert into user(username,password,nickname,picture,job) values(%s)" print(self.__dict__) # 获取子类的属性,也就是表名 table = self.__class__.__getattribute__(self, 'table_name') keys = [] value = [] for k,v in self.__dict__.items(): keys.append(k) value.append(v) print(keys) print(value) sql = "insert into %s(%s) values('%s')" %(table,','.join(keys),"','".join(value)) print(sql) return MyORM().execute(sql) class User(Model): table_name = "user" # 调用父类的构造函数 def __init__(self,**kwargs): super().__init__(**kwargs) class Article(Model): table_name = "article" if __name__ == '__main__': user = User(username="xiaoming1", password="1231", nickname="小明1", picture="2.png", job="全栈1") user.insert() # # 查询user表 # user = User() # # print(user.query()) # print(user.field(["user_id","username","nickname"]).query(user_id=3,username='3@qq.com')) # 查询文章表 # article = Article() # print(article.field(["id","label_name","title"]).query(id=5))
报错信息:
6
收起
正在回答 回答被采纳积分+1
3回答
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星