问题描述
我正在尝试将数据从另一个数据库插入一个数据库。我可以使用选择查询,但是无法将选择查询插入到其他数据库或表中。
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.
在默认情况下会返回 。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"})我们可以 def 供以后使用,首先假设 employee_id 是唯一的 结果,所以我的雇员将是一张地图(如果找不到,则为零):
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"}),然后返回插入的行图(至少在使用PostgreSQL时)。
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))通过ID获取员工的功能,将员工行/映射转换为 other employees_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"})这篇关于Clojure从表中选择记录并将这些记录插入另一个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!