from main.dao.contacts import Contacts
# 获取多条记录,这种写法适合在代码中传参
name ='YangZhi'
q = Contacts.query
q = q.filter(Contacts.name.like("%{}%".format(name)))
rows = q.all()
array =[]for row in rows:id= row.id
name = row.name
tel = row.tel
array.append(str(id)+ name + tel +'\n')print(array)
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import text
rows = Contacts.query.filter(text("name=:name")).params(name='Yanzhi').all()
array =''for row in get_specific_rows:id= row.id
name = row.name
tel = row.tel
array +=str(id)+ name + tel +'\n'return array,200
直接写入SQL语句,并映射成相应类的字段
stmt = text("SELECT name, id, tel FROM contacts where name=:name")# 映射获取的字段到类的属性名
stmt = stmt.columns(Contacts.name, Contacts.id, Contacts.tel)# 写法使用Contacts.query.from_statement(stmt)也是一样的
rows = db.session.query(Contacts).from_statement(stmt).params(name='YangZhi').all()
array =''for row in get_specific_rows:id= row.id
name = row.name
tel = row.tel
array +=str(id)+ name + tel +'\n'return array,200