postgresqlconn.py 文件源码

python
阅读 20 收藏 0 点赞 0 评论 0

项目:heroku-python-boilerplate 作者: chavli 项目源码 文件源码
def insert(self, table_name: str, rows: list) -> int:
        """ inserts the given data into the specified table.

        An individual insert statement is generated per row. The query is handled as a prepared
        statement so multi-inserts are more efficient.

        table_name --
        rows -- list of dicts. each dict representing a row to be inserted

        returns: the number of rows inserted
        """
        n_inserted = 0
        if not self.__conn or not rows:
            raise psycopg2.InterfaceError("null connection")

        try:
            for row in rows:
                columns = "(" + ",".join(row.keys()) + ")"   # "(col1, col2, col3...)"
                params = ",".join(["%s"] * len(row.keys()))  # "%s, %s, %s..."

                query = "insert into {table_name} {columns} select {params}".format(**{
                    "table_name": table_name,
                    "columns": columns,
                    "params": params,
                    })

                n_inserted += self.execute_write_query(query, tuple(row.values()))
            return n_inserted
        except Exception as e:
            tb.print_exc()
            raise(e)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号