How to prevent SQL injection when doing batch inse

2019-08-02 07:37发布

问题:

I have up to 100 items I would like to insert in one batch operation. I am doing it like this:

INSERT INTO MyTable (f1, f2, ..., fk) VALUES
  (v11, v12, ..., v1k),
  (v21, v22, ..., v2k),
  ...
  (vn1, vn2, ..., vnk)

All is fine, but I am building this string by concatenating the values as is, which means my code is vulnerable to SQL injection.

How can I continue using the bulk insert syntax on one hand, yet be protected from the SQL injection?

EDIT 1

I would like to provide a bit more context. The actual SQL that I am going to use (writing the code at this very moment) has the following form:

WITH new_parent AS (
  INSERT into parent (g1, g2, ..., gm) VALUES (v1, v2, ..., vm) RETURNING id
) INSERT INTO MyTable (parent_id, f1, f2, ..., fk) VALUES
  (new_parent.id, v11, v12, ..., v1k),
  (new_parent.id, v21, v22, ..., v2k),
  ...
  (new_parent.id, vn1, vn2, ..., vnk)

回答1:

Use a COPY statement - if it is possible. It is little bit faster, require significantly less memory and it is SQL injection bulletproof - because data use a different channel.