Six-ten database access using SQLAlchemy

Source: Internet
Author: User

A database table is a two-dimensional table that contains multiple rows and columns. If the contents of a table are represented by a Python data structure, a list can be used to represent multiple rows, and each element of the list is a tuple representing a row of records, for example, a id table containing and name user :

[    ('1'Michael'),    ('  2'Bob'),    ('3  "Adam")

The data structure returned by Python's db-api is represented as above.

But it is hard to see the structure of a table with a tuple. If a tuple is represented by a class instance, it is easier to see the structure of the table:

classUser (Object): Def __init__ (self, ID, name): Self.id=ID self.name=name[User ('1','Michael'), User ('2','Bob'), User ('3','Adam')]

This is the legendary ORM technique: Object-relational Mapping, which maps the table structure of a relational database to an object. Isn't it simple?

But who will do the conversion? So the ORM framework emerges.

In Python, the most famous ORM framework is sqlalchemy. Let's take a look at the usage of SQLAlchemy.

First install SQLAlchemy via PIP:

$ pip Install SQLAlchemy

Then, using the table we created in the MySQL test database last time user , try it with SQLAlchemy:

The first step is to import the SQLAlchemy and initialize the dbsession:

# import: fromsqlalchemy Import Column, String, Create_engine fromsqlalchemy.orm Import Sessionmaker fromsqlalchemy.ext.declarative Import declarative_base# base class for creating objects: Base=declarative_base () # Defines the user object:classUser (Base): # table name: __tablename__='User'# Structure of the table: ID= Column (String ( -), primary_key=True) name= Column (String ( -) # Initialize database connection: Engine= Create_engine ('Mysql+mysqlconnector://root:[email protected]:3306/test') # Create Dbsession type: Dbsession= Sessionmaker (Bind=engine)

The above code completes the initialization of the SQLAlchemy and the class definition for each table. If you have more than one table, continue to define other classes, such as school:

class School (Base):     ' School '     = ...     = ...

create_engine()Used to initialize a database connection. SQLAlchemy represents the connection information with a string:

‘数据库类型+数据库驱动名称://用户名:口令@机器地址:端口号/数据库名‘

You only need to replace the user name, password and other information as needed.

Next, let's look at how to add a row of records to a database table.

With ORM, we add a row of records to a database table and can be thought of as adding an User object:

== User (id='5', name='Bob') # Added to session: Session.add (New_user) # Commit is saved to database: Session.commit () # Close session:session.close ()

Visible, the key is to get the session, then add the object to the session, and finally commit and close. DBSessionobject can be considered the current database connection.

How do I query data from a database table? With ORM, the query can be no longer a tuple, but an User object. The query interfaces provided by SQLAlchemy are as follows:

== session.query (User). Filter (user.id=='5'). One () # print type and object's Name property: print (  'type:', type (user) print ('name:' ) , User.Name) # Close Session:session.close ()

The results of the operation are as follows:

Type: <class'__main__. User'>name:bob

As can be seen, ORM is the database table of the row with the corresponding object to establish an association, and convert each other.

Since multiple tables in a relational database can also be used to implement one-to-many, many-to-many associations with foreign keys, the ORM Framework can also provide one-to-many, many-to-many functions between two objects.

For example, if a user has more than one book, you can define a one-to-many relationship as follows:

classUser (Base): __tablename__='User'ID= Column (String ( -), primary_key=True) name= Column (String ( -) # One-to-many: books= Relationship (' Book')classBook (Base): __tablename__=' Book'ID= Column (String ( -), 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 ( -), ForeignKey ('user.id'))

When we query a user object, the books property of the object returns a list containing a number of book objects.

Summary

The purpose of an ORM framework is to automatically convert a row of records from a database table to an object.

The prerequisite for proper use of ORM is to understand the principles of relational databases.

Reference source

do_sqlalchemy.py

Six-ten database access using SQLAlchemy

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.