The so-called ORM is object-relational Mapping, which maps the table results of a relational database to an object.
1. Install SQLAlchemy:
Easy_install SQLAlchemy
2. Import the SQLAlchemy and initialize the dbsession:
# import: From SQLAlchemy import Column, String, create_enginefrom sqlalchemy.orm import Sessionmakerfrom Sqlalchemy.ext.declarative Import declarative_base# creates the base class for the object: base = Declarative_base () # Defines the User object: class User (Base): # Table Name: __tablename__ = ' user ' # table structure: id = column (String), primary_key=true) name = Column ( String (20)) # Initialize database connection: # ' database type + database driver name://user name: password @ machine Address: Port number/database name ' engine = Create_engine (' Mysql+mysqlconnector://root: [Email Protected]:3306/test ') # Create dbsession type: dbsession = Sessionmaker (bind=engine)
3. Add a row of records to the database table:
# Create Session object: Session = Dbsession () # Create new User object: New_user = User (id= ' 5 ', name= ' Bob ') # Add to Session:session.add (New_user) # Commit is saved to database: Session.commit () # Close Session:session.close ()
4. Querying data from the database
# Create session:session = Dbsession () # Create a query, filter is the Where condition, and last Call one () returns a unique row, if all () is called All rows are returned: User = Session.query (user ). Filter (user.id== ' 5 '). One () # print Type and Object Name property: print ' Type: ', type (User) print ' name: ', user.name# close session: Session.close ()
5. Create a one-to-many relationship:
A person has many books: when we query a user object, the books property of the object returns a list containing several book objects
Class User (Base): __tablename__ = ' user ' id = column (string (), primary_key=true) name = Column (String (20 ) # One-to-many: books = relationship (' book ') class book (Base): __tablename__ = ' book ' id = Column (String (20), primary_key=true) name = Column (String) # The Book table for the "many" side is associated to the user table by a foreign key: user_id = Column (String (20), ForeignKey (' user.id '))
Python Learning Notes (16)-ORM Framework (SQLAlchemy)