我正在尝试使用SqlAlchemy(Pymssql作为提供程序)在SQLServerDB上执行简单的原始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')
我以教程中所示的任何方式传递了参数(作为kwargs传递和作为dict传递),但它们都不起作用,当调用execute
方法时,会抛出一个异常,表示{execute
方法一样,似乎是ORM(或者可能是数据提供程序(在本例中是PymSQL))不识别传递给execute
方法的参数,只将查询(不带参数)传递给db引擎(这会导致异常)
我想MSSQL服务器提供程序(Pymssql)可能会有一些问题,因为SQL Server不是SqlAlchemy和Python家族中的头等公民,但没有直接的线索知道是什么导致了这一问题
正如我上面所说的,我也尝试了其他方法
下面是我的第二次尝试(使用连接的execute
方法并将参数作为dict传递):
provider = DataProvider().engine
q = "select url from Crawler.CrawlSource where source=@source"
query = text(q)
result = provider.connect().execute(query, {source :'mysource'})
我的第三次尝试(使用engine对象的execute
方法并以**kwargs方式传递参数):
provider = DataProvider().engine
q = "select url from Crawler.CrawlSource where source=@source"
query = text(q)
result = provider.execute(query, source ='mysource')
我的第四次尝试(使用engine对象的execute
方法并将参数作为dict传递):
provider = DataProvider().engine
q = "select url from Crawler.CrawlSource where source=@source"
query = text(q)
result = provider.execute(query, {source :'mysource'})
我的第五次尝试(创建会话并使用会话的execute
方法并将参数作为dict传递):
provider = DataProvider().engine
session = sessionmaker(bind=provider)()
q = "select url from Crawler.CrawlSource where source=@source"
query = text(q)
result = session.execute(query, {source :'mysource'})
我的第六次尝试(创建会话并使用会话的execute
方法并以**kwargs方式传递参数):
provider = DataProvider().engine
session = sessionmaker(bind=provider)()
q = "select url from Crawler.CrawlSource where source=@source"
query = text(q)
result = session.execute(query, source='mysource')
但正如我前面提到的,所有这些努力都没有奏效,都导致了上述同样的例外
任何帮助都将不胜感激
mssql+pymssql方言似乎支持“pyformat”paramstyle。这对我很有用:
如果使用SQLAlchemy
text
对象,也可以使用“命名”参数样式:text
对象允许我们一致地使用“命名”paramstyle,而不管DB-API层支持的本机paramstyle是什么(例如,%s
对于pymssql,?
对于pyodbc)相关问题 更多 >
编程相关推荐