Python Learning Notes-SqlAlchemy (first draft)

Source: Internet
Author: User

The previous article briefly introduced MySQL's native commands and how to use the Pymysql module in Python. This section provides a brief introduction to SQLAlchemy and his ORM framework. The ORM Framework allows the developer to manipulate the database through the methods of the class without having to use native SQL statements.


Cases

from sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy import  Column, integer, string, foreignkey, uniqueconstraint, indexfrom sqlalchemy.orm  import sessionmaker, relationshipfrom sqlalchemy import create_engineengine  = create_engine ("Mysql+pymysql://yli:[email protected]:3306/mydb",  max_overflow=5) Base  = declarative_base () #  Create a single table Class users (base):     __tablename__ =   ' users '     id = column (integer, primary_key=true)      name = column (String)     extra = column (string))      __table_args__ =  (    uniqueconstraint (' id ',  ' name ',  name= ' Uix_id_name '),         index (' ix_id_name ',  ' name ',   ' extra '),     ) #  one-to-many class favor (Base):    __tablename__ =  ' Favor '      nid = column (integer, primary_key=true)     caption =  Column (String (),  default= ' Red ',  unique=true) Class person (Base):     __ tablename__ =  ' person '     nid = column (integer, primary_key=true)     name = column (String (+),  index=true, nullable=true)      favor_id = column (Integer, foreignkey ("Favor.nid")) #  Many-to-many class  Servertogroup (Base):    __tablename__ =  ' Servertogroup '      Nid = column (integer, primary_key=true, autoincrement=true)     server_ Id = column (Integer, foreignkey (' server.id '))     group_id =  Column (Integer, foreignkey (' GroUp.id ') Class group (Base):    __tablename__ =  ' Group '      id = column (integer, primary_key=true)     name = column ( String ( unique=true, nullable=false), Class server (Base):     __tablename_ _ =  ' server '     id = column (integer, primary_key=true,  Autoincrement=true)     hostname = column (String), unique=true,  Nullable=false)     port = column (integer, default=22) # Create a table Base.metadata.create_all (engine)   #删除表 # base.metadata.drop_all (engine)


Table created by the above command

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/8A/0E/wKiom1glFYPjCL_BAABCvMJmtQo427.png "title=" you. png " alt= "Wkiom1glfypjcl_baabcvmjmtqo427.png"/>


Modified, we can add data and query data

from sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy import  Column, integer, string, foreignkey, uniqueconstraint, indexfrom sqlalchemy.orm  import sessionmaker, relationshipfrom sqlalchemy import create_engineengine  = create_engine ("Mysql+pymysql://yli:[email protected]:3306/mydb",  max_overflow=5) Base  = declarative_base () #  Create a single table Class users (base):     __tablename__ =   ' users '     id = column (integer, primary_key=true)      name = column (String)     extra = column (string))      __table_args__ =  (    uniqueconstraint (' id ',  ' name ',  name= ' Uix_id_name '),         index (' ix_id_name ',  ' name ',   ' extra '),     ) #  one-to-many class favor (Base):    __tablename__ =  ' Favor '      nid = column (integer, primary_key=true)     caption =  Column (String (),  default= ' Red ',  unique=true) Class person (Base):     __ tablename__ =  ' person '     nid = column (integer, primary_key=true)     name = column (String (+),  index=true, nullable=true)      favor_id = column (Integer, foreignkey ("Favor.nid")) #  Many-to-many class  Servertogroup (Base):    __tablename__ =  ' Servertogroup '      Nid = column (integer, primary_key=true, autoincrement=true)     server_ Id = column (Integer, foreignkey (' server.id '))     group_id =  Column (Integer, foreignkey (' GroUp.id ') Class group (Base):    __tablename__ =  ' Group '      id = column (integer, primary_key=true)     name = column ( String ( unique=true, nullable=false), Class server (Base):     __tablename_ _ =  ' server '     id = column (integer, primary_key=true,  Autoincrement=true)     hostname = column (String), unique=true,  Nullable=false)     port = column (integer, default=22) Base.metadata.create_ All (engine) # base.metadata.drop_all (engine) Session = sessionmaker (bind=engine) session =  session () obj = users (name= ' alex111 ', extra= ' sss ') session.add (obj) session.commit () q =  Session.query (users) print (q) ret = session.query (users). All () print (ret) print (ret[0].name) print (ret[0] . ID)


The results are as follows:

"C:\Program files\python3\python.exe" "C:/users/yli/documents/tencent files/38144205/filerecv/filerecv/day12/ s17.py "Select Users.id as users_id, users.name as Users_name, Users.extra as Users_extra from users[<__main__. Users Object at 0x00000259d73aef28>]alex1111


This article is from the "Mapo Tofu" blog, please be sure to keep this source http://beanxyz.blog.51cto.com/5570417/1871672

Python Learning Notes-SqlAlchemy (first draft)

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.