Clojure Selecting records from a table and inserting those records into another table

落花浮王杯 提交于 2019-12-25 16:13:08

问题


I am trying to insert data into one database from a different database. I have the select query working but I haven't been able to take the select query and insert it into a different database and or table.

(jdbc/query db ["select * from employees
                    where employee_id = 1927"]
                {:as-arrays? true})

Now, how do I now insert the above data into another table dynamically?


回答1:


Let's say your employees table looks like this:

create table employees (
    employee_id integer,
    name        text,
    primary key (employee_id)
);
insert into employees (employee_id, name) values (123, 'taylor');

I wouldn't use :as-arrays? true for the query, because the row maps query returns by default are easier to work with.

(jdbc/query db ["select * from employees where employee_id = ?" 123])
;; notice query parameterization; important! ----------------^  ^
=> ({:employee_id 123, :name "taylor"})

And we can def that for use later, taking the first result assuming employee_id is unique, so my-employee will be a single map (or nil if not found):

(def my-employee
  (first (jdbc/query db ["select * from employees where employee_id = ?" 123]))

Now let's assume your other table you want to insert into looks like this:

create table employees_too (
    employee_id integer,
    name        text,
    phone       text, -- just a new column
    primary key (employee_id)
);

Then you could insert that employee row like this:

(db/insert! conn "employees_too"
            (assoc my-employee
                   :phone (str (rand-int 9999999999))))
=> ({:employee_id 123, :name "taylor", :phone "250505207"})

And the inserted row map(s) are returned (at least when using PostgreSQL).

You may want to create reusable functions for these operations:

(defn get-employee [id]
  (first (db/query conn ["select * from employees where employee_id = ?" id])))
(defn employee->employee-too [employee]
  (assoc employee :phone (str (rand-int 99999))))
(defn insert-employee-too [employee-too]
  (db/insert! conn "employees_too" employee-too))

A function to get an employee by ID, a function to transform an employee row/map into the other employees_too table's schema, and a function to insert a row/map into that table. You can tie them all together like this:

(-> (get-employee 123)
    (employee->employee-too)
    (insert-employee-too))
=> ({:employee_id 123, :name "taylor", :phone "8147"})



回答2:


Please see

  • the Clojure Cookbook DB chapter
  • clojure-doc.org SQL page


来源:https://stackoverflow.com/questions/48270893/clojure-selecting-records-from-a-table-and-inserting-those-records-into-another

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