SqlBulkCopy

class SqlBulkCopy(table, *columns)

Performs a PostgreSQL COPY-based bulk insert using a temporary file. Created via SQL.bulk_copy(table, *columns).

Parameters:
  • table – Target table name string.

  • columns – Column name strings defining the column order.

bc = SQL.bulk_copy('films', 'code', 'title', 'did')
count_rows

Number of rows written so far.

fp

The temporary file object containing encoded row data.

write_row(**kwargs)

Write a single row. Keyword arguments map column names to values. Columns not present in kwargs are written as NULL.

Values are encoded as follows:

  • None\N (PostgreSQL NULL)

  • str → UTF-8 encoded with special characters escaped

  • bytes → escaped directly

  • other types → converted via str() then UTF-8 encoded

bc = SQL.bulk_copy('films', 'code', 'title', 'did')
bc.write_row(code='UA502', title='Bananas', did=105)
bc.write_row(code='T_601', title='Yojimbo', did=106)
execute(db)

Seek to the start of the temporary file and execute the COPY using psycopg2’s cursor.copy_from().

Parameters:

db – A psycopg2 connection object.

bc.execute(db)