2323Step 1:
2424start a live connection with DBApi
2525'''
26- ## activate echo option will print out actual SQL statement at each step.
26+ ## activate echo option will print out actual SQL statement at each step, for debugging purposes
2727## to connect to postgresql, create_engine('dialect://username:password@local:port/DBname')
28- db = create_engine ('postgresql://username:password@localhost:5432/dbname' , echo = True )
28+ db = create_engine ('postgresql://username:password@localhost:5432/dbname' , echo = False )
2929
3030'''
3131Step 2:
6363'''
6464Step 3:
6565define ORM
66- CAUION: STEP 3, 4, 5 CAN NOT EXCHANGE AMONGST EACH OTHER. THE SEQUENCE IS DEFINITE
66+ CAUION: STEP 3, 4, 6 CAN NOT EXCHANGE AMONGST EACH OTHER. THE SEQUENCE IS DEFINITE
67+ Here I opened session before instance creation, this is for the purpose of get the
68+ max(id) in the codes table, in case there are already records in the table.
6769'''
68- class Codes (object ):
70+ class Codes_Entity (object ):
6971 __table__ = "codes"
7072 def __init__ (self , id , code ):
7173 self .id = id
@@ -77,24 +79,35 @@ def __repr__(self):
7779Step 4:
7880map between object and relational table.
7981'''
80- mapper (Codes , codes )
82+ mapper (Codes_Entity , codes )
8183metadata .create_all (db )
8284
8385'''
8486Step 5:
87+ start session. And query to get the max(id) in the Code table.
88+ '''
89+ sm = sessionmaker (bind = db , autocommit = False , expire_on_commit = True )
90+ session = scoped_session (sm )
91+ ## the following query means:
92+ ## select max(id) from codes;
93+ ##.scalar() method get the actual data, otherwise it is just a sql statement
94+ ## Note that in the func(), the Table is not the actual name of the table itself
95+ ## in the db, rather, it is the mapped class entity!!!! <-------should be very careful
96+ max_id = session .query (func .max (Codes_Entity .id )).scalar ()
97+
98+ '''
99+ Step 6:
85100Create instances of Codes class
86101'''
87102raw_codes = codeGen (200 )
88103code_list = []
89104for i in range (len (raw_codes )):
90- code_list .append (Codes ( i + 1 , raw_codes [i ]))
105+ code_list .append (Codes_Entity ( max_id + 1 + i , raw_codes [i ]))
91106
92107'''
93- Step 6 :
94- start session. Add records and commit.
108+ Step 7 :
109+ Add records and commit.
95110'''
96- sm = sessionmaker (bind = db , autocommit = False , expire_on_commit = True )
97- session = scoped_session (sm )
98111for code in code_list :
99112 #add will stage all the transactions
100113 session .add (code )
0 commit comments