【Foreword】If you want to use ORM to operate data in the database, the premise is that you have created a new ORM model; that is, the model we have built before https://www.jb51.net/article/218036.htm [ORM operation steps]
【Constructing ORM model objects】user_obj = User( username="use1", password="123456", real_name = "User 1", age=12 ) 【Add to session】# Add an object session.add(user_obj) # Add multiple objects session.add_all([user1,user2,user3]) [The role of session]
[Creating a session]There are two methods, the following code example # Method 1: Instantiate session from sqlalchemy.orm import Session with Session(engine) as session: session.add(User()) session.commit() # Method 2: Create a factory function from sqlalchemy.orm import sessionmaker Session = sessionmaker(engine) with Session.begin() as session: session.add(User()) [Submit data to database]with Session(engine) as session: session.add(user_obj) session.add_all([user1,user1,user1]) session.commit() [Exception occurred, rollback transaction]with Session(engine) as session: session.begin() try: session.add(user1) session.add(user2) except: session.rollback() raise else: session.commit() [Other common methods in Session objects] 1. execute(statement, params=None,*args) executes SQL query 2. delete(instance) physically deletes data 3. get(entity,idnet,*args) returns the ORM object that meets the conditions according to the primary key/None 4. query(*entities,**kwargs) Use ORM query to return Query object This is the end of this article about using ORM to add data in Mysql. For more relevant ORM MySQL database content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: How to use Docker+DockerCompose to encapsulate web applications
>>: Share 20 excellent web form design cases
need: Use vue to realize QR code scanning; Plugin...
Environment Introduction: Ubuntu Server 16.04.2+M...
<br />Related articles: 9 practical suggesti...
1. Nexus configuration 1. Create a docker proxy U...
1. Create a docker network card [root@i ~]# brctl...
Table of contents 1. Introduction 2. Ideas Two wa...
Introduction: This article takes the sample proje...
Table of contents 1. Use the a tag to preview or ...
Table of contents 1. What are microtasks? 2. What...
This should be something that many people have do...
In the previous article, we introduced the MySQL ...
This article uses an example to describe how MySQ...
Table of contents From father to son From son to ...
Table of contents 1. Operation elements 1.1. Chan...
Database SQL optimization is a common problem. Wh...