【问题标题】:BigQuery update how to get number of updated rowsBigQuery更新如何获取更新的行数
【发布时间】:2020-03-17 02:45:47
【问题描述】:

我正在使用 Google Cloud Functions 连接到 Google Bigquery 数据库并更新一些行。云函数是使用 Python 3 编写的。

每当我通过函数运行更新 dml 时,我需要帮助弄清楚如何获取结果消息或更新/更改的行数。有任何想法吗?

from google.cloud import bigquery

def my_update_function(context,data):

    BQ = bigquery.Client()
    query_job = BQ.query("Update table set etc...")
    rows = query_job.result()
    return (rows)

我知道行总是作为 _emptyrowiterator 对象返回。有什么办法可以得到结果或结果消息?文档说我必须从 bigquery 作业方法中获取它。但似乎无法弄清楚。

【问题讨论】:

  • .num_dml_affected_rows 是单一(父)工作的好方法,但是,如果您有多个子工作,@@row_count (system variables) 可能也有用。

标签: python-3.x google-bigquery google-cloud-functions


【解决方案1】:

我认为您正在搜索QueryJob.num_dml_affected_rows。它包含受更新或任何其他 DML 语句影响的行数。如果您只是将其粘贴到您的代码中而不是 return 语句中的 rows 中,您将获得 int 形式的数字,或者您可以创建一些按摩,例如:

return("Number of updated rows: " + str(job_query.num_dml_affected_rows))

希望对你有帮助:)

【讨论】:

  • 哦,谢谢。这是一种更优雅的方式。让我测试一下。
  • 谢谢,但有没有办法访问儿童工作的num_dml_affected_rows?目前,我的num_dml_affected_rows 为 0,我相信这是由于 DML 是在儿童工作中完成的。
【解决方案2】:

似乎在 bigquery Python DB-API 文档中没有提及返回的行。 https://googleapis.dev/python/bigquery/latest/reference.html

我决定使用迂回的方法来处理这个问题,首先生成一个 SELECT 语句来检查 UPDATE 语句中的 WHERE 子句是否匹配。

例子:

from google.cloud.bigquery import dbapi as bq

def my_update_function(context,data):

        try:
            bq_connection = bq.connect()
            bq_cursor = bq_connection.cursor()
            bq_cursor.execute("select * from table where ID = 1")
            results = bq_cursor.fetchone()

            if results is None:
                print("Row not found.")

            else:
                bq_cursor.execute("UPDATE table set name = 'etc' where ID = 1")
                bq_connection.commit()
                bq_connection.close()

        except Exception as e:
            db_error = str(e)

【讨论】:

    猜你喜欢
    • 2021-12-01
    • 2018-05-09
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 2022-12-06
    • 2011-06-28
    • 1970-01-01
    • 2013-09-22
    相关资源
    最近更新 更多