SoFunction
Updated on 2025-03-02

Simple tutorial on using sqlalchemy library under Python's Flask framework

sqlalchemy in flask is more thorough than sqlalchemy encapsulation, and is simpler in some methods

First, import the class library:

View code fragments on CODE derived to my code fragment

  <span style="font-size:18px;">from flask import Flask 
  from  import SQLAlchemy</span>

 


Then, the database path needs to be loaded

View code fragments on CODE derived to my code fragment

  <span style="font-size:18px;">mysqlname='<span style="color: rgb(230, 219, 116); font-family: 'Source Code Pro'; font-size: 13pt; background-color: rgb(39, 40, 34);">mysql://user:[email protected]/student?charset=utf8</span>'</span> 

View code fragments on CODE derived to my code fragment

  <span style="font-size:18px;">app = Flask(__name__) 
  ['SQLALCHEMY_DATABASE_URI'] = mysqlname 
  db = SQLAlchemy(app)</span> 


Through the first two steps, we have connected flask and database together

Next we will link flask with specific tables.

This creates a model model

View code fragments on CODE derived to my code fragment

  &lt;span style="font-size:18px;"&gt;class User(): 
   
    """Storage the number of each alarm type, counting in minutes
     :param source: string , alarm source
     :param network_logic_area: string , the logical network area to which the alarm belongs
     :param start_time: datetime , alarm occurrence time
     """ 
   
    __tablename__ = 'hello' 
    id = ( , primary_key = True) 
    source = ((255) ) 
    network_logic_area = ((255) ) 
    start_time = () 
    count = () 
   
    def __init__(self , source , network_logic_area , start_time , count): 
       = source 
      self.network_logic_area = network_logic_area 
      self.start_time = start_time 
       = count 
   
    def alter(self): 
       += 1;&lt;/span&gt; 

The above code links the falsk with the specific table hello together.

In this class, we first need to specify the table, then list all the columns in this table, and finally define an initialization function to let the data inserted later be used


Now start the specific database operation:

1、insert

View code fragments on CODE derived to my code fragment

  <span style="font-size:18px;">    p = User(........) 
      (p) 
      ()</span> 

A data is constructed through User-like

2、find

Use the primary key to get data:
Code example:

(1)

<User
 u'admin'>

Reverse checking with one exact parameter:
Code example:

peter
=

.filter_by(username='peter').first() 
#Note: The exact query function query.filter_by() is query by passing parameters; other enhanced query functions are (), query by passing expressions.
print() 
#If the data does not exist, return None

Fuzzy query:
Code example:
 

(('@')).all()

[<User
 u'admin'>,
 <User u'guest'>]

Logic non-1:
Code example:
 

peter
=

(
 !=

'peter').first()

print()

Logic non-2:
Code example:
 

from

sqlalchemy import

not_

peter
=

(not_(=='peter')).first()

print()

Logic and:
Code example:

from

sqlalchemy import

and_

peter
=

(and_(=='peter',
 ('@'))).first()

print()

Logical or:
Code example:

from

sqlalchemy import

or_

peter
=

(or_(
 !=

'peter',
 ('@'))).first()

print()

filter_by: This can only put specific conditions in it, not a complex calculation.

Filter: This can put some complex calculations in it

.first: Get the first piece of data

.all: Get out all data

There is another method that can perform operations such as sorting and counting

3. Use SQL statements

You can directly use SQL native statements through the db constructed earlier

View code fragments on CODE derived to my code fragment

  <span style="font-size:18px;">insert_table.(' ..... ')</span> 


4、delete

View code fragments on CODE derived to my code fragment

  <span style="font-size:18px;">me = User(........)</span> 

View code fragments on CODE derived to my code fragment

  <span style="font-size:18px;">(me) 
  ()</span> 

5. Update data

Code example:
 
u
=

()


=

'guest' 
#Updating data and variable assignments is so simple, but it must be an object returned through a query.
()