ORM Operation MySQL

Source: Internet
Author: User

Creating tables and adding data

Import SQLAlchemy
From SQLAlchemy import Create_engine
From sqlalchemy.ext.declarative import declarative_base
From SQLAlchemy import Column, Integer, String
From Sqlalchemy.orm import Sessionmaker


Engine = Create_engine ("Mysql+pymysql://root:[email protected]/test_db", echo=true) #echo =true can view more information
Base = Declarative_base ()
#创建表
Class User (Base):
__tablename__ = ' user ' #表名
id = Column (Integer, Primary_key=true)
Name = Column (String (32))
Password = Column (String (64))
  
    def __repr__ (self): #显示ORM查询执行后的结果 (no memory address returned by this method)
Return '%s:%s '% (Self.name, Self.password)


Base.metadata.create_all (engine) #创建表结构

#创建连接
Session_class = Sessionmaker (bind=engine) #创建与数据库的会话session class, notice that the return is a class, not an instance
Session = Session_class () #生成session实例 #可以先理解成curson游标
#查询
# data = Session.query (User). Filter (User.ID < 2). All () #是一个列表
data = Session.query (User). Filter (User.ID > 2). Filter (User.ID < 5)

Print (data)
#插入数据
User_obj1 = User (name= ' Lizhao ', password= ' lizhaoqwe123 ') #生成要创建的数据对象
User_ibj2 = User (name= ' test ', password= ' testqwe123 ')
Session.add (USER_OBJ1)
Session.add (USER_IBJ2)
Session.commit () #必须commit之后才会添加数据

ORM Operation MySQL

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.