SQL alchemy Introduction
SQL alchemy is a concrete realization of the idea of product orm
orm: object-relational mapping ideological Object Relational Mapping
The database is a resource and object-oriented classes and objects are associated with
A table === "a class
A data === 'object
The idea is to achieve a specific product is more famous in python with sqlalchemy,
SQL alchemy is a third-party packages, we need to be installed by cmd input pip3 install sqlalchemy
Some basic operations we can operate to achieve classes and objects in the database
Create a table of operation
SQLAlchemy Import create_engine from from sqlalchemy.ext.declarative Import declarative_base from SQLAlchemy Import Column, Integer, String, DateTime, the Enum, ForeignKey, UniqueConstraint, ForeignKeyConstraint, Index from sqlalchemy.orm Import sessionmaker, Relationship # first create a connection object database engine = create_engine ( '+ MySQL pymysql: // root: [email protected]:? 3306 / DB4 charset = utf8', max_overflow = 5) # need to specify which connection a number of conditions, including a user name and password to connect ip port, also you need to specify connection pool max_overflow, specify the maximum number of connections # Note that: specifies the character encoding does not have an impact there, you need to specify the encoding when creating a database # create a base class, other classes inherit this class can be mapped with tables base = declarative_base () class the classes (Base): # Create a table to specify a table name __tablename__ = 'classes' # field and the predetermined specified types and constraints ID = the Column (Integer, primary_key = True, AUTOINCREMENT = True) CNAME = the Column (String (32), Nullable = False, server_default = '') # Note that: set the default value shall be server_default, and if the set of type int the default value must () turn about with STR addr = column (String (32), Nullable = False, server_default = '', index = True) # to one column add unique index or index may be directly provided i.e. directly column in can classes_id the Column = (Integer, a ForeignKey (Teacher.id)) # is added plus disposed inside, by a ForeignKey () method to set the # key this is an out-many relationship, if it is one foreign key relationships conditions also need to add a unique index # EG: classes_id the Column = (Integer, a ForeignKey (Teacher.id), uNIQUE = True) __table_args__ = ( the UniqueConstraint (sname, Phone, name = 'uix_snname_phone'), index ( 'ix_addr', addr) ) # want to set up joint joint index is a unique index or words it must be set in the __table_args__ # by UniqueConstraint, index complete indexing Base.metadata.drop_all (engine) # delete Base.metadata.create_all (engine) # create # Finally, create a mapping tables and delete tables required by the above two methods # Note that: # 1, delete only removes the table above there mappings, if you have a database table is not mapped, it is deleted can not afford the # If you originally empty database, it will not error # 2, then if you created this table name already exists, then it will not cover the creation, equivalent to not execute
The basic data change search deletions
Queries must first create an object session of a query for converting commands and help us get the results Session = sessionmaker (bind = egine) # about the need to bind the connection object session = Session () advance Statement: In addition to the query, other operations must to session.commit to the real operation execution to the database # ------------------------------------ ------------------------------------ Add the Add () add_all () # need to create data, in the corresponding program is the object, there is no increment column attributes set by other key assignment obj = Classes (cname = 'class two years') session.add (obj) # the Add a row of data (an object to add ) session.add_all ([obj, obj2]) # add_all () adding a plurality of data, with a list of them loaded # ------------------------- ----------------------------------------------- query query ( ) # check all, take all the fields res = session.query (Classes) .all ( ) # returns a list, containing objects session.query (Classes) # print out the SQL statement res = session.query (Classes) .first ( ) # is taken first, it returns an object # check all, take specific word RES = session.query (Classes.cname) .all () # returns a list, containing tuple element your query group stood value res = session.query (Classes.cname) .first ( ) # get the first one, the return tuple # fetch the equivalent of all the fields in the SQL statement have * to take a specific field is equivalent to a column or some columns # difference between the two is obtained: All fields are objects come back, come back a particular field tuple # specific conditions have to look at the following query # ---------------- -------------------------------------------------- ------ modify Update () # Found first find the need to change it, and then modified by Update session.query (the Classes) .filter (Classes.id ==. 1) .Update ({ 'CNAME': ' XXX '}) # Update placed in a dictionary k, v corresponding table and column values inside # --------------------------- --------------------------------------------- delete the delete () # delete also need to first find out the value, and then delete session.query (Classes) .filter (Classes.id == 1) .delete ()
session.commit()
session.close()
Other queries
In the SQL query methods Alchemy has a corresponding substantially to achieve the SQL statement, as follows
where
where conditions query filter () filter_by () # brackets writing determination conditions (may be plural), both of the following differences session.query (the Classes) .filter (Classes.id ==. 1) # is put in parentheses specific which list which column to a value session.query (the Classes) .filter_by (the above mentioned id = 1) # brackets put the column name = value (equivalent to an assignment, check in more than one table and column names appear at the same time there will be phase trouble) session.query (the Classes) .filter (~ == Classes.id. 1) # is negated mean ~
like
Fuzzy matching the wildcard like like () session.query (the Classes) .filter (Classes.cname.like ( "King%%")) # in the filter, a column can be used to point out the fuzzy matching method like
between and
and BETWEEN BETWEEN () session.query (the Classes) .filter (Classes.id.between (1,2)) # and the like, as is also to point out by a column, is closed interval BETWEEN
in / not in
Not in IN_ notin_ in session.query (the Classes) .filter (Classes.id.in _ ([. 1])) session.query (the Classes) .filter (Classes.id.notin _ ([1, 2,4])) # also you can point out the column by the specific method # Note that, in_ or notin_ must be put inside iterables
limit
limit slice session.query (the Classes) [2:. 6: 2] # implemented with a microtome, and slicing the same list, the specified cut length and step
order by
order_by by Order () session.query (the Classes) .order_by (Classes.id.desc ()) # order_by by way of the query, which can specify which column sorting, can point out a method in ascending or descending asc desc # same brackets where you can also specify multiple column sorting, consistent usage and SQL statement usage
group by (having)
HAVING GROUP_BY by Group () HAVING () # want to use aggregate functions, it must be imported func method from sqlalchemy.sql Import func session.query (func.max (Classes.id)). GROUP_BY (Classes.cname) .having (func.max (Classes.id)>. 3) # aggregate functions used by the query must point out func # group in accordance with the packet into the column, and finally can point out HAVING () to query the secondary
Even table query
Even table substantially even table session.query (the Classes, Student) # directly link the two tables, there will be a problem Cartesian product # via the foreign key is determined session.query (Classes, Student), filter (Classes.id == Student.class_id) left connecting join () session.query (Student) .join (the Classes) # join into one table corresponds to only join the inner connection session.query (Student) .join (Classes, isouter = True) # to join the isouter into True becomes connected to the left but the value if you want to get the name of the class, and that class will have to put the table in the query
Regular check pegging
Positive check pegging Relationship # add a hidden attribute table has a foreign key (an attribute is defined in the column) attr = Relationship ( 'the Classes', backref = 'hideattr') # Relationship which are associated with the first you you table foreign key, backref is hidden columns other table case class the classes (Base): __tablename__ = 'classes' ID = the column (Integer, primary_key = True, AUTOINCREMENT = True) CNAME = the column (String (32), Nullable = false, server_default = '') class Student (Base): ID = the Column (Integer, primary_key = True, AUTOINCREMENT = True) sname = the Column (String (32), Nullable = false, server_default = '') class_id = the Column (Integer , a ForeignKey (Classes.id)) class_type = Relationship ( 'the Classes', backref = 'XXX') # so by Student Student this table.Classes class_id find a corresponding row, the point may be an attribute Classes By binding the foreign key table (Student) in hidden columns is bound to check foreign key table (Classes) in a row is called a forward queries # and Classes can meet this Classes.id xxx point by point how many students # point out that a list, the list of students stood object through a foreign key table is bound (Classes) in hidden column check how many matching table (student) line is called reverse lookup
SQL alchemy Introduction
SQL alchemy is a concrete realization of the idea of product orm
orm: object-relational mapping ideological Object Relational Mapping
The database is a resource and object-oriented classes and objects are associated with
A table === "a class
A data === 'object
The idea is to achieve a specific product is more famous in python with sqlalchemy,
SQL alchemy is a third-party packages, we need to be installed by cmd input pip3 install sqlalchemy
Some basic operations we can operate to achieve classes and objects in the database
Create a table of operation
SQLAlchemy Import create_engine from from sqlalchemy.ext.declarative Import declarative_base from SQLAlchemy Import Column, Integer, String, DateTime, the Enum, ForeignKey, UniqueConstraint, ForeignKeyConstraint, Index from sqlalchemy.orm Import sessionmaker, Relationship # first create a connection object database engine = create_engine ( '+ MySQL pymysql: // root: [email protected]:? 3306 / DB4 charset = utf8', max_overflow = 5) # need to specify which connection a number of conditions, including a user name and password to connect ip port, also you need to specify connection pool max_overflow, specify the maximum number of connections # Note that: specifies the character encoding does not have an impact there, you need to specify the encoding when creating a database # create a base class, other classes inherit this class can be mapped with tables base = declarative_base () class the classes (Base): # Create a table to specify a table name __tablename__ = 'classes' # field and the predetermined specified types and constraints ID = the Column (Integer, primary_key = True, AUTOINCREMENT = True) CNAME = the Column (String (32), Nullable = False, server_default = '') # Note that: set the default value shall be server_default, and if the set of type int the default value must () turn about with STR addr = column (String (32), Nullable = False, server_default = '', index = True) # to one column add unique index or index may be directly provided i.e. directly column in can classes_id the Column = (Integer, a ForeignKey (Teacher.id)) # is added plus disposed inside, by a ForeignKey () method to set the # key this is an out-many relationship, if it is one foreign key relationships conditions also need to add a unique index # EG: classes_id the Column = (Integer, a ForeignKey (Teacher.id), uNIQUE = True) __table_args__ = ( the UniqueConstraint (sname, Phone, name = 'uix_snname_phone'), index ( 'ix_addr', addr) ) # Want to set up a joint unique index or index joint, then it must be set in __table_args__ # by UniqueConstraint, Index complete index to establish Base.metadata.drop_all (engine) # delete Base.metadata.create_all (engine) # create # Finally, create a mapping tables and delete tables required by the above two methods # Note that: # 1, delete only removes the table above there mappings, if you have a database table is not mapped, it is deleted can not afford the # If you originally empty database, it will not error # 2, then if you created this table name already exists, then it will not cover the creation, equivalent to not execute
The basic data change search deletions
Queries must first create an object session of a query for converting commands and help us get the results Session = sessionmaker (bind = egine) # about the need to bind the connection object session = Session () advance Statement: In addition to the query, other operations must to session.commit to the real operation execution to the database # ------------------------------------ ------------------------------------ Add the Add () add_all () # need to create data, in the corresponding program is the object, there is no increment column attributes set by other key assignment obj = Classes (cname = 'class two years') session.add (obj) # the Add a row of data (an object to add ) session.add_all ([obj, obj2]) # add_all () adding a plurality of data, with a list of them loaded # ------------------------- ----------------------------------------------- query query ( ) # check all, take all the fields res = session.query (Classes) .all ( ) # returns a list, containing objects session.query (Classes) # print out the SQL statement res = session.query (Classes) .first ( ) # is taken first, it returns an object # check all, take specific word RES = session.query (Classes.cname) .all () # returns a list, containing tuple element your query group stood value res = session.query (Classes.cname) .first ( ) # get the first one, the return tuple # fetch the equivalent of all the fields in the SQL statement have * to take a specific field is equivalent to a column or some columns # difference between the two is obtained: All fields are objects come back, come back a particular field tuple # specific conditions have to look at the following query # ---------------- -------------------------------------------------- ------ modify Update () # Found first find the need to change it, and then modified by Update session.query (the Classes) .filter (Classes.id ==. 1) .Update ({ 'CNAME': ' XXX '}) # Update placed in a dictionary k, v corresponding table and column values inside # --------------------------- --------------------------------------------- delete the delete () # delete also need to first find out the value, and then delete session.query (Classes) .filter (Classes.id == 1) .delete ()
session.commit()
session.close()
Other queries
In the SQL query methods Alchemy has a corresponding substantially to achieve the SQL statement, as follows
where
where conditions query filter () filter_by () # brackets writing determination conditions (may be plural), both of the following differences session.query (the Classes) .filter (Classes.id ==. 1) # is put in parentheses specific which list which column to a value session.query (the Classes) .filter_by (the above mentioned id = 1) # brackets put the column name = value (equivalent to an assignment, check in more than one table and column names appear at the same time there will be phase trouble) session.query (the Classes) .filter (~ == Classes.id. 1) # is negated mean ~
like
Fuzzy matching the wildcard like like () session.query (the Classes) .filter (Classes.cname.like ( "King%%")) # in the filter, a column can be used to point out the fuzzy matching method like
between and
and BETWEEN BETWEEN () session.query (the Classes) .filter (Classes.id.between (1,2)) # and the like, as is also to point out by a column, is closed interval BETWEEN
in / not in
Not in IN_ notin_ in session.query (the Classes) .filter (Classes.id.in _ ([. 1])) session.query (the Classes) .filter (Classes.id.notin _ ([1, 2,4])) # also you can point out the column by the specific method # Note that, in_ or notin_ must be put inside iterables
limit
limit slice session.query (the Classes) [2:. 6: 2] # implemented with a microtome, and slicing the same list, the specified cut length and step
order by
order_by by Order () session.query (the Classes) .order_by (Classes.id.desc ()) # order_by by way of the query, which can specify which column sorting, can point out a method in ascending or descending asc desc # same brackets where you can also specify multiple column sorting, consistent usage and SQL statement usage
group by (having)
HAVING GROUP_BY by Group () HAVING () # want to use aggregate functions, it must be imported func method from sqlalchemy.sql Import func session.query (func.max (Classes.id)). GROUP_BY (Classes.cname) .having (func.max (Classes.id)>. 3) # aggregate functions used by the query must point out func # group in accordance with the packet into the column, and finally can point out HAVING () to query the secondary
Even table query
Even table substantially even table session.query (the Classes, Student) # directly link the two tables, there will be a problem Cartesian product # via the foreign key is determined session.query (Classes, Student), filter (Classes.id == Student.class_id) left connecting join () session.query (Student) .join (the Classes) # join into one table corresponds to only join the inner connection session.query (Student) .join (Classes, isouter = True) # to join the isouter into True becomes connected to the left but the value if you want to get the name of the class, and that class will have to put the table in the query
Regular check pegging
Positive check pegging Relationship # add a hidden attribute table has a foreign key (an attribute is defined in the column) attr = Relationship ( 'the Classes', backref = 'hideattr') # Relationship which are associated with the first you you table foreign key, backref is hidden columns other table case class the classes (Base): __tablename__ = 'classes' ID = the column (Integer, primary_key = True, AUTOINCREMENT = True) CNAME = the column (String (32), Nullable = false, server_default = '') class Student (Base): ID = the Column (Integer, primary_key = True, AUTOINCREMENT = True) sname = the Column (String (32), Nullable = false, server_default = '') class_id = the Column (Integer , a ForeignKey (Classes.id)) class_type = Relationship ( 'the Classes', backref = 'XXX') # so by Student Student this table.Classes class_id find a corresponding row, the point may be an attribute Classes by binding the foreign key table hidden (Student) column check is bound foreign key table (the Classes) is called a positive line to the query # and Classes can meet this Classes.id xxx point by point how many students # point out that a list, the list of students stood object through a foreign key table is bound (Classes) in hidden column check how many matching table (student) line is called reverse lookup