繁体   English   中英

在 SQLAlchemy 中的原始 SQL 查询中实现占位符

[英]Implement placeholders in raw SQL queries in SQLAlchemy

如何在 SQLAlchemy 的原始 SQL 查询中实现占位符?

try:
    username: 'Pat'
    email: 'pat@gmail'
    password: 'pat'
    engine.execute("INSERT INTO users (username, email, password) VALUES (:username, :email, :password)", 
    {"username": username, "email": email, "password": password})
    session = db_session()
    session.commit()
    print('Inserted into db')
except:
    print('not inserted')

占位符被指定为 arguments 来execute

from sqlalchemy.sql import text

engine.execute(text("INSERT INTO ..."), username=username, email=email, password=password)

.. 或者如果您想将您的字典扩展为 arguments,您可以使用**arguments ,其中arguments = {"username": username, "email": email, "password": password}

确保将查询包装在text()调用中以扩展占位符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM