Working with MySQL via SQLAlchemy

Source: Internet
Author: User

# Installing PIP3 Install SQLAlchemy

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

# Create a connection
Engine = Create_engine ("Mysql+pymysql://root:[email protected]/testdb", encoding= "Utf-8", Echo=true)

# Generate ORM Base class
Base = Declarative_base ()

Class User (Base):
__tablename__ = ' user '
id = Column (integer,primary_key=true)
Name = Column (String (32))
Password = Column (String (64))

Base.metadata.create_all (Engine) # CREATE TABLE structure

Session_class = Sessionmaker (bind=engine) # Create a class with a database connection session
Session = Session_class () # generates session instance #cursor

User_obj = User (name= "Dennis", password= "abc123") #生成要创建的数据对象
User_obj2 = User (name= "Alex", password= "ABCD")
Print (user_obj.name,user_obj.id)
Session.add (User_obj)
Session.add (USER_OBJ2)

Session.commit ()

Working with MySQL via SQLAlchemy

Related Article

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.