How to prevent SQL injection when doing batch insert in PostgreSQL?

守給你的承諾、 提交于 2019-12-11 05:27:39

问题


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.



来源:https://stackoverflow.com/questions/19476208/how-to-prevent-sql-injection-when-doing-batch-insert-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!