【问题标题】:How to check in pyodbc package if last impala statement was a select statement?如果最后一个 impala 语句是 select 语句,如何检查 pyodbc 包?
【发布时间】:2020-05-14 11:01:50
【问题描述】:

我想要一个基于 pyodbc 包的函数,它对 impala 运行一个查询,如果有要获取的东西,则获取结果,否则,只需执行该语句。不幸的是,我不知道如何检查我是否有东西要取。

def execute_my_query(connection, query):
    cur = connection.cursor()
    cur.execute(query)
    res = cur.fetchall()
    return res

不幸的是,如果我执行了没有结果集的操作,例如:

execute_my_query(con, 'drop table if exists my_schama.my_table')

它失败并返回没有结果集的错误。所以我想检查是否有我应该返回的结果,如果没有理由返回任何东西,则跳过。

【问题讨论】:

    标签: python pyodbc impala


    【解决方案1】:

    与此同时,我已经能够产生一种似乎以所需方式工作的解决方案。

    根据pyodbcdocumentation 中为游标属性description 编写的内容,属性“对于不返回行的操作或未调用执行方法之一的操作将为None”。

    请注意,如果您想改用 rowcount 属性,这在 impala 中不起作用,因为即使存在非空结果集,您也会得到 rowcount=-1

    因此,可以将问题中的函数重写为:

    def execute_my_query(connection, query):
        res = None 
        cur = connection.cursor()
        cur.execute(query)
        if cur.description is not None:
            res = cur.fetchall()
        return res
    

    话虽如此,如果有更好的处理方法,我还是很想听听。

    【讨论】:

      猜你喜欢
      • 2020-07-27
      • 2020-10-27
      • 2014-02-11
      • 2021-01-05
      • 2013-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-17
      相关资源
      最近更新 更多