# 有的复杂sql 用orm写不出来---》用原生sql查询
# 原生sql查询,查出的结果是对象
# 原生sql查询,查询结果列表套元组文章来源:https://www.toymoban.com/news/detail-636648.html
准备工作
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine
engine = create_engine("mysql+pymysql://root:123@127.0.0.1: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': '3333@qq.com'})
session.commit()
print(cursor.lastrowid)
执行原生sql方式二:
(以后都用session操作---》socpe_session线程安全)一般不用文章来源地址https://www.toymoban.com/news/detail-636648.html
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()
到了这里,关于sqlalchemy执行原生sql的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!