orm的作用
听说可以不用写sql语句就可以实现对数据库的操作(当然这也是orm的作用),于是就有了这篇文章...
下面是简单的代码
from pymysql import connect
class Field(object):
def __init__(self, args):
self.args = args
class ChangeClass(type):
def __new__(cls, class_name, super_name, attrs):
print(attrs)
sql_dict = dict()
for key, value in attrs.items():
if isinstance(value, Field):
sql_dict[key] = value.args
print(sql_dict)
attrs['sql_dict'] = sql_dict
attrs['table_name'] = class_name.lower()
return type.__new__(cls, class_name, super_name, attrs)
class Table(object, metaclass=ChangeClass):
# 把table设置为父类
# # 让此字典自动生成
# # sql_dict = {"id": "int unsigned", "name": "varchar(30)"}
# # 这里是属性,写成键值的形式
# table_name = "kaka"
# # 写成元祖方便区别写入元素,方便查找
# id = ("int unsigned",)
# name = ("varchar(30)",)
# # sql_dict = {"id": id, "name": name}
def create_table(self):
# 1 连接数据库
# 2 操作数据库
# 3 关闭
# 连接数据库
conn = connect(host='localhost', port=3306, database='zxc', user='root', password='mysql', charset='utf8')
# 获取游标
cs1 = conn.cursor()
# 创建字典保存键值关系
sql_list = list()
# 获取字典内的值
for key, values in self.sql_dict.items():
sql_list.append("%s %s" % (key, values))
# sql_list.append(key, values)
# user(id int unsigned, name varchar(20))
# 操作数据库
sql = """ create table if not exists %s(%s) """ % (self.table_name, ",".join(sql_list))
print(sql)
cs1.execute(sql)
# 提交!!!
conn.commit()
# 获取数据
# data = cs1.fetchall()
# 关闭
cs1.close()
conn.close()
def insert(self, **kwargs):
print(kwargs)
# (2.创建列表,我们想要得到的值在调用函数时输入,此时分析一下,输入方式是键值对,所以用**kwargs,接下来就是取出对应的键与值了)
list_key = list()
list_value = list()
# (3.把取出的值放进对应的列表里,这里要注意在数据库中的值都是以)
for key, value in kwargs.items():
list_key.append(key)
list_value.append(""" '%s' """ % str(value)) #这里会出错sequence item 0: expected str instance, int found在另一篇文章会说
#list_value.append(value)
# 连接数据库
conn = connect(host='localhost', port=3306, database='zxc', user='root', password='mysql', charset='utf8')
# 获取游标
cs1 = conn.cursor()
# 操作数据库(1.清楚要获得什么类型的内容-->答案是列表!ok,我们去创建列表)
sql = """insert into %s(%s) values(%s);""" % (self.table_name, ",".join(list_key), ",".join(list_value))
print(sql)
rows = cs1.execute(sql)
# 提交!!!
conn.commit()
# 关闭
cs1.close()
conn.close()
# #################################框架################################################################
class Student(Table):
name = Field('varchar(30)')
num = Field('int')
# class User(Table):
# name = ("varchar(30)",)
# age = ("int",)
def main():
student = Student()
student.create_table()
student.insert(name='zxc', num=22)
if __name__ == '__main__':
main()
网友评论