首页 > 数据库 >Flask中使用SQL

Flask中使用SQL

时间:2022-12-29 13:13:11浏览次数:40  
标签:return name Flask SQL db session user 使用 id

 

转自:https://blog.csdn.net/huhinghao123/article/details/124272093?spm=1001.2101.3001.6661.1&utm_medium=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1-124272093-blog-113934713.pc_relevant_aa&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1-124272093-blog-113934713.pc_relevant_aa&utm_relevant_index=1

from flask import Flask
from flask_sqlalchemy import SQLAlchemy


app = Flask('web_name')
app.config.from_object(webconfig)
db = SQLAlchemy(app)


# 查询
def get_user(account, pwd):
sql = ('select id,name,account,pwd,createtime ' \
+ 'from publisher ' \
+ 'where account = "{0}" and pwd = "{1}"').format(account, pwd)

data = db.session.execute(sql).first()

if data != None:
user = Publisher()
user.id = data['id']
user.name = data['name']
user.account = data['account']
user.pwd = data['pwd']
user.createtime = data['createtime']
return user
else:
return None

 

# 插入、修改、删除
def create_token(user,token):
sql = ('insert into token ' \
+ '(tokenvalue,createtime,publisher_id) values ' \
+ '("{0}",now(),{1})').format(token, user.id)

affect = db.session.execute(sql).rowcount
db.session.commit()
if affect != 0 :
return True
else:
return False

 

# 插入后,查询最后插入的数据
def add_node(publish_id,message,name):
sql1 = ('insert into node ' \
+ '(message,createtime,name,state) values ' \
+ '("{0}",now(),"{1}",1)').format(message,name)
affect = db.session.execute(sql1).rowcount

if affect == 1:
sql2 = 'SELECT LAST_INSERT_ID()'
node_id = db.session.execute(sql2).first()[0]

sql3 = ('insert into publish_node '\
+'(publisher_id , node_id) values '\
+'({0},{1})').format(publish_id,node_id)
affect2 = db.session.execute(sql3).rowcount
if affect2 == 1:
db.session.commit()
return True
else:
return False
else:
return False
所以这样声明sql会优雅许多

 

标签:return,name,Flask,SQL,db,session,user,使用,id
From: https://www.cnblogs.com/ltsgsh/p/17012260.html

相关文章