Sqlalchemy _ getting started with sqlalchemy
Database operation software, similar to pdo in php, is more flexible and complex than pdo. It can correspond the tables in the database to the classes in the program one by one for convenient calling. If the class can be written in the early stage, do not write SQL later; install
pip install flask_sqlalchemy
Create a table:
1 from flask_sqlalchemy import SQLAlchemy 2 from sqlalchemy import * 3 from sqlalchemy. orm import * 4 # some files imported above may not be used; 5 engine = create_engine ("mysql: // root: root @ localhost: 3306/flask? Charset = utf8 ", echo = True) 6 metadata = MetaData (engine) 7 goods = Table ('goods ', metadata, 8 Column ('id', Integer, primary_key = True), 9 Column ('name', String (20), 10 Column ('fullname', String (40), 11) 12 metadata. create_all ()
Insert data:
1 #-*-coding: UTF-8-*-2 from flask_sqlalchemy import SQLAlchemy 3 from sqlalchemy import * 4 from sqlalchemy. orm import * 5 # link to the database and initialize the object 6 engine = create_engine ("mysql: // root: root @ localhost: 3306/flask? Charset = utf8 ", echo = True) 7 metadata = MetaData (engine) 8 9 users_table = Table (" goods ", metadata, autoload = True) # This should be the initialization table 10 I = users_table.insert () # Call the insert () method in the object and generate the statement: INSERT INTO goods (id, name, fullname) VALUES (% s, % s, % s) 11 result = I .exe cute (name = "summer", fullname = "736960938@qq.com") # Pass in the parameter and execute 12 print (result)
Query data 1. If you see this method used to insert data, you can also query it;
1 users_table = Table ("goods", metadata, autoload = True) 2 I = users_table.select () 3 result = I .exe cute (name = "xiaoge ") 4 # It seems awkward to query this method. The object contains objects and the query result 5 print (result) cannot be seen directly)
2. Create a ing between the table and the class
1 goods_table = Table ("goods", metadata, autoload = True) 2 ''' 3 establishes the ing between the Table and class 4 ''' 5 class Goods (object ): 6 def _ repr _ (self): 7 return "% s (% r, % r)" % (self. _ class __, self. name, self. fullname) 8 mapper (Goods, goods_table) 9 ''' link establishment ended ''' 10 session = create_session () 11 query = session. query (Goods) 12 u = query. filter_by (name = "xiaoge "). first () 13 print (u. fullname)
Object. _ dict _ view the content of the object, and query all data without recursion:
1 goods_table = Table ("goods", metadata, autoload = True) 2 ''' 3 establishes the ing between the Table and class 4 ''' 5 class Goods (object ): 6 def _ repr _ (self): 7 return "% s (% r, % r)" % (self. _ class __, self. name, self. fullname) 8 mapper (Goods, goods_table) 9 ''' link establishment ended ''' 10 session = create_session () 11 query = session. query (Goods) 12 u = query. all () 13 for I in u: # Return multiple objects, traverse to 14 print (I. name)