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.
- from sqlalchemy.ext.declarative import declarative_base
- BASE = declarative_base()
With this base class, you can define the model class for the users table.
- class User(BASE):
- __tablename__ = "users"
- id = Column(INTEGER, primary_key=True)
- name = Column(CHAR(127))
- 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.
- from sqlalchemy.orm import sessionmaker
- from sqlalchemy import create_engine
- ENGINE = create_engine("mysql://root:zaq12wsx@localhost:3306/mydb?charset=utf8",
- convert_unicode=True)
- Session = sessionmaker(bind=ENGINE, autocommit=False, autoflush=False)
- session = Session()
- user = User()
- user.name = "user1"
- user.password = "password"
- session.add(user)
- 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.
- mysql> select * from users;
- +----+-------+----------+
- | id | name | password |
- +----+-------+----------+
- | 1 | user1 | password |
- +----+-------+----------+
- 1 row in set (0.00 sec)
Query the records
- user = session.query(User).filter_by(name="user1").first()
- print"%s %s" % (user.name, user.password)
update record
- user = session.query(User).filter_by(name="user1").first()
- user.password = "newpassword"
- session.commit()
- user = session.query(User).filter_by(name="user1").first()
- session.delete(user)
- session.commit()