Python 在SQLAlchemy中的原始SQL查询中实现占位符
如何在SQLAlchemy中的原始SQL查询中实现占位符Python 在SQLAlchemy中的原始SQL查询中实现占位符,python,sqlalchemy,Python,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, "pa
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')
占位符作为要执行的参数提供: 。。或者,如果要将字典扩展为参数,可以使用**参数,其中参数={username:username,email:email,password:password} 将查询包装在文本调用中也是一种很好的做法:
。。。因为这允许对语句进行独立于引擎的解析。您好,MatsLindh,我非常感谢您的回复;然而我主要关心的是你写的论点部分。如何将sql查询与之关联。如果可以,请重新编写代码以进行说明。非常感谢。我就是这么做的:values={username:Pat,email:pat@gmail.com,password:pat}engine.executeINSERT进入用户用户名,电子邮件,密码值:username,:email,:password,值,但它仍然没有运行。在这种情况下,您必须执行**值才能将其扩展为username=pat,email=pat@gmail.com, ... 在幕后。但与其这样做,不如直接给出参数来执行…,username=Pat,email=pat@gmail.com, ... 除非你已经把它作为另一个电话的字典了。在这种情况下,使用**作为前缀,将参数解包为指定的参数,以便执行。
.execute("INSERT INTO ...", username=username, email=email, password=password)
from sqlalchemy.sql import text
....
engine.execute(text("SELECT ...."), username=username, email=email, password=password