Adding Objects
In the previous chapters of SQLAlchemy ORM, we have learnt how to declare mapping and create sessions. In this chapter, we will learn how to add objects to the table.
We have declared Customer class that has been mapped to customers table. We have to declare an object of this class and persistently add it to the table by add() method of session object:
- c1 = Customers(name = 'Ravi Kumar', address = 'Station Road Nanded', email = 'ravi@gmail.com')
- session.add(c1)
- session.commit()
To add multiple records, we can use add_all() method of the session class:
- session.add_all([
- Customers(name = 'Komal Pande', address = 'Koti, Hyderabad', email = 'komal@gmail.com'),
- Customers(name = 'Rajender Nath', address = 'Sector 40, Gurgaon', email = 'nath@gmail.com'),
- Customers(name = 'S.M.Krishna', address = 'Budhwar Peth, Pune', email = 'smk@gmail.com')]
- )
- session.commit()
- testdb=# SELECT * FROM CUSTOMERS;
- id | name | address | email
- ----+------------+---------------------+----------------
- 1 | Ravi Kumar | Station Road Nanded | ravi@gmail.com
- (1 row)
* SQLAlchemy ORM - Declaring Mapping & Creating Session
沒有留言:
張貼留言