简体   繁体   中英

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

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?

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 :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"})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM