How to insert json data with postgrex?

Hi i’m new in elixir and i have this error when I insert data to Json Column

(FunctionClauseError) no function clause matching in Postgrex.DefaultTypes."-inlined-encode_params/3-"/3    
    
    The following arguments were given to Postgrex.DefaultTypes."-inlined-encode_params/3-"/3:
    
        # 1
        %{"Nombre" => "Pistache", "Temp" => 100}
    
        # 2
        [Postgrex.Extensions.JSON]
    
        # 3
        []

My code in iex is something like this

Mix.install([:postgrex,:jason])
{:ok, pid} = Postgrex.start_link(hostname: "localhost", username: "dbapg", password: "dbpass", database: "db")
sql = "insert into temperatura values( default,now(),$1)"
{:ok, _result} = Postgrex.prepare_execute(pid,"",sql,  %{"Nombre" => "Pistache", "Temp" => 100})

What i’m doing wrong?

Why not use Ecto? Postgrex is a little lower-level… I barely ever interact with it directly.

To answer your specific question, you called a function which was expecting data in a different structure than you gave. There should be a couple lines in the error code which show all the patterns that the function expects to match on.

But just use Ecto.

2 Likes

You might have to pass it like this

[%{"Nombre" => "Pistache", "Temp" => 100}]

I think the third argument is a list of parameters

2 Likes

Thanks you are right!!!

[%{"Nombre" => "Pistache", "Temp" => 100}]

I dont like ORM and not all people need it. I am learning… yes, but all programing languajes have access for Databases with ‘drivers’. i wanna know how to use it.

Ecto is not an ORM, it’s a data mapper. Meaning it’s much more lightweight and less opinionated.

4 Likes

O.O i didnt know. I will check it. Thanks

This is a little write up I did over at the little orange-themed website.

While it discusses my uses more than anything, I enumerate what I’ve come to see Ecto as being (which may/or may not align more broadly to the maintainers and the community).

As @dimitarvp points out: it’s not an ORM and is very much better.

Having said that though, I think it’s a very good idea to understand the Postgrex library nonetheless… it’s used by Ecto and if you need something lower level it’s always good to have that knowledge in your toolbox.