ORM "Object Relational Mapping", that is, object-relational mapping, is to map a row of a relational database to an object, that is, a class corresponding to a table, so that the code is simpler to write, do not directly manipulate the SQL statement.
ORM Module: orm.py
#!/usr/bin/env python#-*-coding:utf-8-*-'Simple ORM using Metaclass'__author__='Michael Liao'classField (object):def __init__(self, Name, Column_type): Self.name=name Self.column_type=Column_typedef __str__(self):return '<%s:%s>'% (self.__class__.__name__, Self.name)classStringfield (Field):def __init__(self, name): Super (Stringfield, self).__init__(Name,'varchar (+)')classIntegerfield (Field):def __init__(self, name): Super (Integerfield, self).__init__(Name,'bigint')classModelmetaclass (type):def __new__(CLS, name, bases, attrs):ifname=='Model': returnType.__new__(CLS, name, bases, Attrs)Print('Found Model:%s'%name) Mappings=dict () forKvinchAttrs.iteritems ():ifisinstance (V, Field):Print('Found Mapping:%s ==>%s'%(k, V)) Mappings[k]=v forKinchMappings.iterkeys (): Attrs.pop (k) attrs['__mappings__'] = Mappings#Saving mappings for properties and columnsattrs['__table__'] = Name#Assuming that the table name and class name match returnType.__new__(CLS, name, bases, Attrs)classModel (dict):__metaclass__=Modelmetaclassdef __init__(Self, * *kw): Super (Model, self).__init__(**kw)def __getattr__(self, key):Try: returnSelf[key]exceptKeyerror:RaiseAttributeerror (R"' Model ' object has no attribute '%s '"%key)def __setattr__(self, Key, value): Self[key]=valuedefSave (self): fields=[] Params=[] args= [] forKvinchSelf.__mappings__. Iteritems (): Fields.Append (v.name) params.append ('?') Args.append ("'"+str (GetAttr (self, k, None)) +"'") SQL="insert into {table} ({keys}) values ({value})". Format (table=self.__table__, keys=','. Join (Fields), value=','. Join (args))Print('SQL:%s'%sql)Print('ARGS:%s'%str (args))returnSQL#Testing Code:classProductInfo (Model): ProductID= Integerfield ('ProductID') ProductName= Stringfield ('ProductName') ParentID= Integerfield ('ParentID') Clicknum= Integerfield ('Clicknum') Test= ProductInfo (productid=12345, productname='Iphone', parentid=1111, clicknum=99999) SQL=Test.save ()ImportCx_oracledb= Cx_oracle.connect ('Aidba/[email protected]') Cursor=db.cursor () cursor.execute (SQL) Db.commit ()
Execute Python orm.py
[email protected] pythonscript]$ python orm.py
Found Model:productinfo
Found Mapping:parentid ==> <IntegerField:parentID>
Found Mapping:clicknum ==> <IntegerField:clickNum>
Found mapping:productname ==> <StringField:productName>
Found Mapping:productid ==> <IntegerField:productID>
Sql:insert into ProductInfo (Clicknum,productname,productid,parentid) VALUES (' 99999 ', ' Iphone ', ' 12345 ', ' 1111 ')
ARGS: ["' 99999 '", "' Iphone '", "' 12345 '", "' 1111 '"]
Database view
Related:
Python connection to Oracle database relies on third-party modules Cx_oracle
Installation of cx_oracle:
(1) pip:pip install Cx_oracle
(2) Rpm:rpm-ivh cx_oracle-5.1.1-11g-py26-1.x86_64.rpm requires an Oracle version of the installation package
Configuration of environment variables:
All environment variables for Oracle users are required, so it is best to use them under Oracle users, plus a new line in the. bash_profile file under Oracle users.
Export Ld_library_path= $ORACLE _home/lib:/usr/lib:/usr/lib
Save then source . Bash_profile
One of the problems encountered:
Save before Modification ()
defSave (self): fields=[] Params=[] args= [] forKvinchSelf.__mappings__. Iteritems (): Fields.Append (v.name) params.append ('?') args.append (str (GetAttr (self, k, None ))) SQL="insert into%s (%s) values ('%s ')"% (self.__table__,','. Join (Fields),','. Join (args))Print('SQL:%s'%sql)Print('ARGS:%s'%str (args))returnSql
Execution results
Sql:insert into ProductInfo (Clicknum,productname,productid,parentid) VALUES (' 2222,michael,12345,1111 ')
ARGS: [' 2222 ', ' Michael ', ' 12345 ', ' 1111 ']
Traceback (most recent):
File "orm.py", line-in <module>
Cursor.execute (SQL)
Cx_oracle.databaseerror:ora-00947:not enough values
There is a problem with the execution of SQL format args.append (str (GetAttr (self, k, none)) modified to Args.append ("'" +str (GetAttr (self, k, none) + "'") to resolve.
Python ORM implementation and Python connect to Oracle under Linux