首页 > 解决方案 > 如何使用计数器计算表中插入记录的数量并使用python脚本打印每个作业中插入记录的数量

问题描述

我想使用计数器或任何方法计算表中插入记录的数量,并打印使用 python 脚本运行的每个作业中插入记录的计数。示例代码如下所示..请建议一些相同的解决方案..

 with Postgresql.Database(connection_pool) as db:
   --count number of rows inserted in bazaarvoicereviews table and print the count for every job run
   db.insert('externaldb.bazaarvoicereviews',data=rdata)
--count number of rows inserted in bazaarvoicereviewsresponses table and print the count for every job run
   for rs in _ClientResponses:
       db.insert('externaldb.bazaarvoicereviewsresponses',data=rs)
--count number of rows inserted in bazaarvoicereviewscomments table and print the count for every job run
   for rc in _ClientComments:
      db.insert('externaldb.bazaarvoicereviewscomments',data=rc)

标签: pythonpython-3.xpostgresqlgoogle-cloud-platformgoogle-cloud-sql

解决方案


如果使用psycopg2,则可以从光标中获取行数:

cursor.execute(statement)
rowcount = cursor.rowcount
conn.commit()

完整示例:

import psycopg2

class CustomPostgres:
    def __init__(self):
        self.conn_string = "connection_string"
        self.conn = psycopg2.connect(self.conn_string)
        self.cursor = self.conn.cursor()

    def insert_with_rowcount(self, statement):
        self.cursor.execute(statement, params)
        rowcount = self.cursor.rowcount
        self.conn.commit()
        return rowcount


推荐阅读