sqlalchemy执行原生sql

# 有的复杂sql 用orm写不出来---》用原生sql查询

# 原生sql查询,查出的结果是对象
# 原生sql查询,查询结果列表套元组

 准备工作

from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine

engine = create_engine("mysql+pymysql://root:[email protected]:3306/db001", max_overflow=0, pool_size=5)
Session = sessionmaker(bind=engine)
session = Session()

执行原生sql方式一:

# 查询方式一:
cursor = session.execute('select * from users')
result = cursor.fetchall()
print(result) #列表套元组
# 添加
cursor = session.execute('insert into users(name,email) values(:name,:email)',
                         params={"name": 'lqz', 'email': '[email protected]'})
session.commit()
print(cursor.lastrowid)

执行原生sql方式二:

(以后都用session操作---》socpe_session线程安全)一般不用

conn = engine.raw_connection()
cursor = conn.cursor()
cursor.execute(
     "select * from app01_book"
)
result = cursor.fetchall()

执行原生sql方式三:

res = session.query(User).from_statement(text("SELECT * FROM boy where name=:name"))
.params(name='lqz').all()

你可能感兴趣的:(flask,sql,数据库)