2019年4月11日 星期四

[ Python 文章收集 ] SQLAlchemy ORM - Adding Objects

Source From Here 
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: 
  1. c1 = Customers(name = 'Ravi Kumar', address = 'Station Road Nanded', email = 'ravi@gmail.com')  
  2. session.add(c1)  
Note that this transaction is pending until the same is flushed using commit() method: 
  1. session.commit()  
Following is the complete script to add a record in customers table: 
>>> c1 = Customers(name = 'Ravi Kumar', address = 'Station Road Nanded', email = 'ravi@gmail.com')
>>> session.add(c1)
>>> session.commit()
2019-04-10 22:04:42,241 INFO sqlalchemy.engine.base.Engine INSERT INTO customers (name, address, email) VALUES (%(name)s, %(address)s, %(email)s) RETURNING customers.id
2019-04-10 22:04:42,241 INFO sqlalchemy.engine.base.Engine {'name': 'Ravi Kumar', 'address': 'Station Road Nanded', 'email': 'ravi@gmail.com'}
2019-04-10 22:04:42,242 INFO sqlalchemy.engine.base.Engine COMMIT

To add multiple records, we can use add_all() method of the session class: 
  1. session.add_all([  
  2.    Customers(name = 'Komal Pande', address = 'Koti, Hyderabad', email = 'komal@gmail.com'),   
  3.    Customers(name = 'Rajender Nath', address = 'Sector 40, Gurgaon', email = 'nath@gmail.com'),   
  4.    Customers(name = 'S.M.Krishna', address = 'Budhwar Peth, Pune', email = 'smk@gmail.com')]  
  5. )  
  6.   
  7. session.commit()  
Below shows that the records are persistently added in customers table: 
  1. testdb=# SELECT * FROM CUSTOMERS;  
  2. id |    name    |       address       |     email  
  3. ----+------------+---------------------+----------------  
  4.   1 | Ravi Kumar | Station Road Nanded | ravi@gmail.com  
  5. (1 row)  
Supplement 
SQLAlchemy ORM - Declaring Mapping & Creating Session

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...