Sqlalchemy is easy to use
First, sqlalchemy connects to the database.
Installation:
Pip install sqlalchemy
Sqlalchemy View version:
Import sqlalchemy
Sqlalchemy.__version__
Sqlalchemy connection to the database:
From sqlalchemy import create_engine
HOST='127.0.0.1'
PORT='3306'
DATABASE='test'
USERNAME='test'
PASSWORD='pass'
DB_URL = 'mysql+pymysql:// {}: {} @ {}: {} / {}? charset=utf8'.format (
USERNAME, PASSWORD, HOST, PORT, DATABASE
)
Engin = create_engine (DB_URL, echo=False)
The simple process for sqlalchemy to create a table:
1. Create a base class
From sqlalchemy.ext.declarative import declarative_base
Base = declarative_base ()
two。 Create a class
From sqlalchemy import Column, Integer, String
Class User (Base):
_ _ tablemame__ = 'users' # the name of the data table
Id = Column (Integer, Sequence ('user_id_seq'), Primary_key=True) # set as the primary key
Name = Column (String (20), nullable=False) # non-empty
Password = Column (String (255), nullable=False)
Create a table:
Base.metadata.create_all (engine)
Create an object
Zs_user = User (name='zs', fullname='ZhangSan', password='password')
Zs.name
Zs
Create Session
From sqlalchemy.orm import sessionmaker
Session = sessionmaker (bind=engine)
Add update object
Add a zs_user object to the session
Session.add (zs_user)
Through conditional query
Zs = session.query (User). Filter_by (name='zs'). First ()
You can use the add_all () function to add multiple User objects at one time,
Session.add_all (
User (name='ls', fullname='lisi', password='pass')
User (name='ww', fullname='wangwu', password='pass')
)
View the status waiting for submission:
Session.new
Commit changes to the database:
Session.commit ()