【问题标题】:How to count number of inserted records in table using counter and print the count of inserted record in each job run using python script如何使用计数器计算表中插入记录的数量并使用python脚本打印每个作业中插入记录的数量
【发布时间】:2020-07-19 11:37:59
【问题描述】:

我想使用计数器或任何方法计算表中插入记录的数量,并打印使用 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)

【问题讨论】:

  • 你使用哪个 postgressql 包?
  • 我们用来加载数据的pyscopg2包
  • 我们还创建了自己的模块:Postgresql 将数据加载到表中

标签: python python-3.x postgresql google-cloud-platform google-cloud-sql


【解决方案1】:

如果您使用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

【讨论】:

  • 我认为它不适用于我的代码...使用 Postgresql.Database(connection_pool) 作为数据库: --count 插入 bazaarvoicereviews 表中的行数并打印每个作业运行数据库的计数。 insert('externaldb.bazaarvoicereviews',data=rdata) for rs in _ClientResponses: db.insert('externaldb.bazaarvoicereviewsresponses',data=rs) for rc in _ClientComments: db.insert('externaldb.bazaarvoicereviewscmets',data=rc)
  • 当然,如果不改变你的 Postgresql 类的实现,它是行不通的
  • 请分享您的插入实现,以便我可以帮助您添加它..
  • def insert(self, table, data, returned=None): """插入一条记录""" cols, vals = self._format_insert(data) sql = 'INSERT INTO %s (% s) VALUES(%s)' % (table, cols, vals) sql += self._returning(returning) cur = self.execute(sql, list(data.values())) 如果返回,则返回 cur.fetchone() else cur.rowcount
  • 请把它作为您问题的一部分分享,没有清晰的代码 sn-p 很难理解。
猜你喜欢
  • 1970-01-01
  • 2011-08-18
  • 2020-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-01
相关资源
最近更新 更多