如何在SQLAlchemy中执行原始SQL?
我有一个python web应用程序,它运行在烧瓶上,并通过SQLAlchemy与数据库连接.
我需要一种方法来运行原始SQL.该查询涉及多个表连接以及内联视图.
我试过了:
connection = db.session.connection()
connection.execute( <sql here> )
Run Code Online (Sandbox Code Playgroud)
但我不断收到网关错误.
我正在尝试使用 SqlAlchemy(以及 Pymssql 作为提供程序)在 SQL-Server 数据库上执行简单的原始 SQL 查询。
这是我的第一次尝试(使用execute连接方法并以 **kwargs 方式传递参数):
provider = DataProvider().engine
q = "select url from Crawler.CrawlSource where source=@source"
query = text(q)
result = provider.connect().execute(query, source ='mysource')
Run Code Online (Sandbox Code Playgroud)
我以教程中显示的任何方式传递了参数(作为 kwargs 传递并作为 dict 传递),但是它们都不起作用,并且当execute调用方法时抛出异常,表示'Must declare the scalar variable' @source好像没有参数传递给execute方法,似乎是 ORM (或者可能是数据提供程序(在本例中为 pymssql))无法识别传递给的参数execute方法的参数,并且仅将查询(不带参数)传递给数据库引擎(这会导致异常)。
我猜想 MSSQL-Server 提供程序 (Pymssql) 可能存在一些问题,因为 SQL-Server 不是 SqlAlchemy 和 Python 家族中的一等公民,但没有直接线索可能导致此问题。
正如我上面所说,我也尝试了其他方法
这是我的第二次尝试(使用execute连接方法并将参数作为字典传递):
provider = DataProvider().engine
q = "select url from Crawler.CrawlSource where source=@source"
query …Run Code Online (Sandbox Code Playgroud)