Yuan class, sqlalchemy inquiry

Import SQLAlchemy
 from sqlalchemy.ext.declarative Import declarative_base
 # Create Connection instance 
DB = sqlalchemy.create_engine ( " MySQL + pymysql: the root @: @ 123 localhost / sqlalchemydb " )
 # "+ database module database type: // user: password @ host / library name " 
# definition table 
    # define a metaclass inheritance class 
Base = declarative_base (db) 

    # start defining tables 
class the User (Base):
     __tablename__ = " the User " 
    the above mentioned id = sqlalchemy.Column (sqlalchemy.Integer, primary_key = true) 
    name = sqlalchemy.Column (sqlalchemy.String (32)) 

IF  the __name__ == " __main__ " : 
    base.metadata.create_all (DB) 


# for CRUD 
# similar pymysql cursor Cursor 
from sqlalchemy.orm Import sessionmaker 

# bound connection 
Cursor = sessionmaker (= the bind DB) # give when a class of 

the session = Cursor () # instantiation 

# by 
# User = the User ( 
#      ID =. 1, 
#      name = "Border" 
# ) 
# 
# session.add (User) 
# Session.commit () 
# session.add_all([
#     User(id = 2, name = "老赵"),
#     User(id = 3, name = "老李")
# ])
# session.commit()
#
# all_data = session.query(User).all() #查所有
# print(all_data) #得到对象
# for data in all_data:
#     print("id:%s__name:%s"%(data.id,data.name))

many_data = session.query(User).filter_by(id = 1) #查多条
data, = many_data
print("id:%s__name:%s" % (data.id, data.name))
# for data in many_data:
#     Print ( "ID: s__name%:% S"% (data.id, data.name)) 

# Data = session.query (the User) .get (ident =. 3) # a check, a master key can only check 
# Print ( "the above mentioned id:% s__name:% S"% (data.id, data.name)) 

# delete 
    # to query a 
# the Data = session.query (the User) .get (ident = 3) 
#      # and then delete the 
# session.delete (the Data) 
#      # then the commit operation 
# Session.commit () 
# change 
    # to query a 
# the Data = session.query (the User) .get (ident = 2) 
#      # and then delete the 
# data.name = "Li" 
#      # then the commit operation 
# Session.commit ()

Moto类

import pymysql

class Field(object):
    def __init__(self,name,column_type):
        self.name = name
        self.column_type = column_type
    def __str__(self):
        return "<%s:%s>"%(self.name,self.column_type)

class StringField(Field):
    def __init__(self,name):
        super(StringField,self).__init__(name,"varchar(100)")

class IntegerField(Field):
    def the __init__ (Self, name): 
        . Super (IntegerField, Self) the __init__ (name, " int " ) 

class ModelMetaClass (type):
     DEF  __new__ is (CLS, name, bases, attrs):
         '' ' 
        class name:: param name 
        : param bases: class inheritance 
        : param attrs: the class attribute 
        : return: 
        '' ' 
        IF name == " Model " :
             return of the type. __new__ (CLS, name, bases, attrs) 
        Mapping = dict () # empty dictionary 
        for k, v inattrs.items (): # traversal attribute 
            IF the isinstance (V, Field): # determines whether the attribute instance Field 
                mapping [K] = V # Add to mapping them 
        for K in mapping.keys (): # Returns all keys 
            attrs. POP (K) # remove attributes from among 
        attrs [ " __mapping__ " ] = Mapping   # is set to save the field attributes __mapping__ 
        attrs [ " __table__ " ] = name
         return type. __new__ is (CLS, name, bases, attrs) 

class the Model (dict, metaclass = ModelMetaClass):
    def __init__(self,**kwargs):
        self.db = pymysql.connect(
            host = "localhost",
            user = "root",
            password = "123",
            database = "test"
        )
        self.cursor = self.db.cursor()
        super(Model,self).__init__(**kwargs)

    def __getattr__(Self, Key):
         return Self [Key] 

    DEF  __setattr__ (Self, Key, value): 
        Self [Key] = value 

    DEF Save (Self): 
        Fields = [] # empty list field for storing 
        args = [] # Empty list field for storing a value 
        for K, V in Self. __mapping__ .items (): 
            fields.append (V.NAME) 
            args.append (getattr (Self, K, None)) 
        SQL = " INSERT INTO% S (% S) values (% S) " % ( 
            Self. __table__ ,
            ",".join(fields),
            ",".join([repr(str(i)) for i in args]
               )) #sql拼接
        self.cursor.execute(sql)
        print(sql)
    def __del__(self):
        '''
        回收内存
        '''
        self.db.commit()
        self.cursor.close()
        self.db.close()

class Student(Model):
    name = StringField("name")
    room_id = IntegerField("room_id")

u = Student(name = "老边",room_id = 18)
u.save()

 

Guess you like

Origin www.cnblogs.com/wutanghua/p/11047924.html