如何使用elixir中的原始查询在postgres中插入字符串数组

时间:2017-06-09 10:21:35

标签: postgresql elixir ecto

我试图使用Elixir Ecto.Adapters.SQL.query插入postgres,查询由字符串数组组成。但它确实插入了postgres,但不是作为字符串列表,而是单个字符串。 即如果标签包含[" abc"," xyz"],它会在postgres中插入为abcdef而不是数组。

重要的是,我没有使用架构或迁移。简单的原始查询。

需要在postgres中插入的地图

  response_map=  %{"description" => "des33", "id" => 158,
  "inserted_at" => "2017-06-09T10:19:03.904572", "tags" => ["abc","xyz"],
  "title" => "test 1", "updated_at" => "2017-06-09T10:19:03.904578"}

我使用的代码

%{"description" => desc, "id" => id, "title" => title, "tags" =>  tags}=response_map
Ecto.Adapters.SQL.query!(Repo,"insert into test values ('#{id}','#{title}','#{desc}','#{tags}')") 

1 个答案:

答案 0 :(得分:0)

您绝不应在查询中使用字符串插值。您正在打开自己的SQL注入攻击。使用参数化查询,您将修复SQL注入,并使其适用于数组:

Ecto.Adapters.SQL.query!(Repo, "insert into test values ($1, $2, $3, $4)", [id, title, desc, tags]) 
相关问题