SQLALchemy study notes (flask environment)

First, the database connection

dialect+driver://username:password@host:port/database

Fixed connection formats: DB_URI = "mysql + pymysql: // {username}: {password} @ {host}:? {Port} / {db} charset = utf8" .format

from sqlalchemy import create_engine

HOSTNAME = '127.0.0.1'
PORT = '3306'
DATABASE = 'complaint'
USERNAME = 'root'
PASSWORD = 'xinzhi'

# dialect+driver://username:password@host:port/database
DB_URI = "mysql+pymysql://{username}:{password}@{host}:{port}/{db}?charset=utf8".format(username=USERNAME,password=PASSWORD,host=HOSTNAME,port=PORT,db=DATABASE)

engine = create_engine(DB_URI)

Determine whether the connection is successful

conn = engine.connect()
result = conn.execute('select 1')
print(result.fetchone())

Two, ORM Introduction

 ORM : Object Relationship Mapping. Vernacular: the object model and database table mapping

   

1. Create a base class with a `declarative_base` ORM The` engine`.
Import sqlalchemy.ext.declarative from declarative_base
Engine = create_engine (DB_URI)
Base = declarative_base (Engine)
2. `Base` use this class to write their own ORM class as a base class. To define `__tablename__` class attribute to specify the model is mapped to the table name in the database.
the Person class (Base):
__tablename__ = 'Person'
3. Creating an attribute table to map to the field, all the tables need to be mapped to attributes should Column type:
class the Person (Base):
__tablename__ = 'Person'
 in this ORM model to create some property, to one mapping with the fields in the table. These attributes must be sqlalchemy provided us with good data types.
= the Column ID (Integer, primary_key = True, AUTOINCREMENT = True)
name = the Column (String (50))
Age the Column = (Integer)
4. Use `Base.metadata.create_all ()` to map the model into the database.
5. By using `Base.metadata.create_all ()` mapping model to the database, even if the field changes the model, not remapped.

# 1. Create an ORM model, this model must inherit from sqlalchemy ORM provides us with a good base class 
class the Person (Base):
     __tablename__ = ' the Person ' 
    # 2. create some properties in the ORM model, come with the table one mapping fields. These attributes must be sqlalchemy provided us with good data types. 
    Column = the above mentioned id (Integer, primary_key = True, AUTOINCREMENT = True) 
    name = Column (String (50 )) 
    Age = Column (Integer) 
    Country = Column (String (50 ))
 # 3. creates good ORM model, mapped to database. 
Base.metadata.create_all ()

 Three, session CRUD

1. Construction of session objects: all operations and ORM database must be implemented by `session` called session object, and acquires the session object by the following code:
from sqlalchemy.orm Import sessionmaker

engine = create_engine(DB_URI)
session = sessionmaker(engine)()

2. Add objects:
* create an object, i.e. creating a data:
P = the Person (name = 'zhiliao', Age = 18 is, Country = 'China')
* add the object to `session` session object:
the session. the Add (P)
* the session objects do commit operation (submitted):
Session.commit ()
* added in one portion a plurality of data:
P1 = the Person (name = 'zhiliao1', Age =. 19, Country = 'China')
the Person = P2 (name = 'zhiliao2', Age = 20 is, Country = 'China')
session.add_all ([P1, P2])
Session.commit ()
3. Find the object:
# the lookup table corresponding to a model All data:
all_person = session.query (the Person) .all ()
# filter_by using query conditions do
all_person = session.query (the Person) .filter_by (name = 'zhiliao') All ().
# done using filter conditions queries
all_person = session.query (Person) .filter ( person.name == 'zhiliao'). all ()
# Get method using lookup data, based on the get method to find the id, returns only one data or None
person = session.query (the Person) .get (primary_key)
# using the first method to obtain a first set of data results
person = session.query (the Person) .first ()
4. modify Object

First, find the object from the database, and then put this data to modify the data you want, you can finally do commit operation to modify the data.
= session.query Person (the Person) .first ()
PERSON.NAME = 'ketang'
Session.commit ()
5. The deleted object

You will need to remove the data from the database to find out, and then use `session.delete` method to put this data is deleted from the session, and finally do commit operation on it.
= session.query Person (the Person) .first ()
Session.delete (Person)
Session.commit ()

# dialect+driver://username:password@host:port/database
DB_URI = "mysql+pymysql://{username}:{password}@{host}:{port}/{db}?charset=utf8".format(username=USERNAME,password=PASSWORD,host=HOSTNAME,port=PORT,db=DATABASE)

engine = create_engine(DB_URI)

Base = declarative_base(engine)

# Session = sessionmaker(engine)
# session = Session()

session = sessionmaker(engine)()


class Person(Base):
    __tablename__ = 'person'
    id = Column(Integer,primary_key=True,autoincrement=True)
    name = Column(String(50))
    age = Column(Integer)
    country = Column(String(50))

    def __str__(self):
        return "<Person(name:%s,age:%s,country:%s)>" % (self.name,self.age,self.country)

# session:会话

#
def add_data():
    p1 = Person(name='zhiliao1',age=19,country='china')
    p2 = Person(name='zhiliao2',age=20,country='china')
    session.add_all([p1,p2])
    session.commit()

#
def search_data():
    all_person = session.query(Person).all()
    for p in all_person:
        print(p)
    all_person = session.query(Person).filter_by(name='zhiliao').all()
    for x in all_person:
        print(x)
    all_person = session.query(Person).filter(Person.name=='zhiliao').all()
    for x in all_person:
        print(x)
    person = session.query(Person).first()
    print(person)

#
def update_data():
    person = session.query(Person).first()
    person.name = 'ketang'
    session.commit()

#
def delete_data():
    person = session.query(Person).first()
    session.delete(person)
    session.commit()


if __name__ == '__main__':
    # add_data()
    # search_data()
    # update_data()
    delete_data()

 

Guess you like

Origin www.cnblogs.com/iamorz/p/12456137.html