Inserting PostgreSQL arrays with Clojure

后端 未结 3 1249
情话喂你
情话喂你 2021-02-04 10:25

I can\'t find a way to insert Postgres\' array type with Clojure.

(sql/insert! db :things {:animals [\"cow\" \"pig\"]})

Didn\'t work which I ki

3条回答
  •  广开言路
    2021-02-04 10:57

    to use insert! to insert a vector of strings you must create an object (from the vector of strings) that implements java.sql.Array. You can use java.sql.Connection.createArrayOf to create such object

    (def con (sql/get-connection db))
    
    (def val-to-insert 
        (.createArrayOf con "varchar" (into-array String ["cow", "pig"]))
    
    (sql/insert! db :things {:animals val-to-insert})
    

    and

    clojure.java.jdbc's docs on execute! said

    (execute! db-spec [sql & params] :multi? false :transaction? true)
    (execute! db-spec [sql & param-groups] :multi? true :transaction? true)
    

    Your must put your sql string in a vector to make it work.

    (sql/execute! db ["INSERT INTO things (animals) VALUES ('{\"cow\", \"pig\"}')"])
    

提交回复
热议问题