使用SqlAlchemy执行原始查询(在SQLServer数据库和Pymssql上)时,传递无法识别的参数并引发SQL错误

2024-09-26 18:06:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用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')

但正如我前面提到的,所有这些努力都没有奏效,都导致了上述同样的例外

任何帮助都将不胜感激


Tags: 方法textfromurlsourceexecute参数where
1条回答
网友
1楼 · 发布于 2024-09-26 18:06:05

mssql+pymssql方言似乎支持“pyformat”paramstyle。这对我很有用:

import sqlalchemy as sa

engine = sa.create_engine("mssql+pymssql://@localhost:49242/myDb")

sql = "SELECT word FROM vocabulary WHERE language = %(lang)s"
params = {'lang': 'Greek'}
with engine.begin() as conn:
    result = conn.execute(sql, params).fetchall()
    print(result)
    # [('γιορτή',), ('ηλεκτρονικός υπολογιστής',)]

如果使用SQLAlchemytext对象,也可以使用“命名”参数样式:

sql = sa.sql.text("SELECT word FROM vocabulary WHERE language = :lang")
params = {'lang': 'Greek'}
with engine.begin() as conn:
    result = conn.execute(sql, params).fetchall()
    print(result)
    # [('γιορτή',), ('ηλεκτρονικός υπολογιστής',)]

text对象允许我们一致地使用“命名”paramstyle,而不管DB-API层支持的本机paramstyle是什么(例如,%s对于pymssql,?对于pyodbc)

相关问题 更多 >

    热门问题