sqlalchemy learning (4) ORM model and database table additions, deletions and changes

At present, many mainstream languages ​​have implemented the library package of ORM Object Relational Mapper. The main function of ORM is to map each record in a database table into an object. All database operations are converted into object operations. This increases the readability and safety of the code. Of course, the performance will be lower than directly executing the sql command . This article introduces the ORM operation of SQLAlchemy. The version of SQLAlchemy needs to be above 1.1.


Before executing the code behind, please make sure that you have created a table named users according to the introduction of the previous blog post.


In ORM, each table in the database corresponds to a model class. And these model classes need to inherit a base class named declarative base class. We need to get this base class through the following code.


[python]  view plain copy  
  1. from sqlalchemy.ext.declarative import  declarative_base  
  2.   
  3. BASE = declarative_base()  



With this base class, you can define the model class for the users table.

[python]  view plain copy  
  1. class User(BASE):  
  2.     __tablename__ = "users"  
  3.   
  4.     id = Column(INTEGER, primary_key=True)  
  5.     name = Column(CHAR(127))  
  6.     password = Column(CHAR(127))  

In the above code, the __tablename__ class member variable indicates that the User class corresponds to the users table of the database. The following three class member variables are all Column objects, corresponding to the three fields of the table.


Note: By default, the name of the Column object in User is the same as the name of the database table field. If the two are inconsistent, you need to pass in the name parameter in the constructor of the Column object.


add record


The following code describes how to add records to a database table.

[python]  view plain copy  
  1. from sqlalchemy.orm import sessionmaker  
  2. from sqlalchemy import create_engine  
  3.   
  4. ENGINE = create_engine("mysql://root:zaq12wsx@localhost:3306/mydb?charset=utf8",  
  5.                            convert_unicode=True)  
  6. Session = sessionmaker(bind=ENGINE, autocommit=False, autoflush=False)  
  7.   
  8. session = Session()  
  9.   
  10. user = User()  
  11. user.name = "user1"  
  12. user.password = "password"  
  13. session.add(user)  
  14. session.commit()  

Lines 4-8 of the code are used to create the session object. Note that we disabled the autocommit feature of the session object.

Lines 10-12 of the code create a User object. This object has 3 member variables, namely id, name and password. Consistent with the class member variable names of the three Column objects in the three User classes.

Line 14 of the code is to add the newly created user object. Note, however, that since the auto-commit function of the session is disabled, the database is not really updated after executing this line of code. The database is not actually updated until after line 15 of the code is executed.


Below is the updated result of the database.


[plain]  view plain copy  
  1. mysql> select * from users;  
  2. +----+-------+----------+  
  3. | id | name  | password |  
  4. +----+-------+----------+  
  5. |  1 | user1 | password |  
  6. +----+-------+----------+  
  7. 1 row in set (0.00 sec)  


Query the records


[python]  view plain copy  
  1. user = session.query(User).filter_by(name="user1").first()  
  2. print"%s %s" % (user.name, user.password)   
The session.query method in the code will return a Query object. After that, call the filter_by method of the Query object to query. It still returns the Query object. Finally, call the first method of the Query object to obtain the first record of the query record. Returns None if the query record is empty.


update record

[python]  view plain copy  
  1. user = session.query(User).filter_by(name="user1").first()  
  2. user.password = "newpassword"  
  3. session.commit()  


Delete Record

[python]  view plain copy  
  1. user = session.query(User).filter_by(name="user1").first()  
  2. session.delete(user)  
  3. session.commit()  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325981753&siteId=291194637