加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sql – 如何使用Clojure JDBC插入Postgres枚举值?

发布时间:2020-12-12 16:38:51 所属栏目:MsSql教程 来源:网络整理
导读:例如,这里是PostgreSQL中的一个产品表,状态为枚举: create type product_status as enum ('InStock','OutOfStock');create table product ( pid int primary key default nextval('product_pid_seq'),sku text not null unique,name text not null,descripti
例如,这里是PostgreSQL中的一个产品表,状态为枚举:
create type product_status as enum ('InStock','OutOfStock');

create table product (
    pid            int primary key default nextval('product_pid_seq'),sku            text not null unique,name           text not null,description    text not null,quantity       int not null,cost           numeric(10,2) not null,price          numeric(10,weight         numeric(10,2),status         product_status not null
);

插入产品的典型Clojure代码将是:

(def prod-12345 {:sku "12345"
                 :name "My Product"
                 :description "yada yada yada"
                 :quantity 100
                 :cost 42.00
                 :price 59.00
                 :weight 0.3
                 :status "InStock"})

(sql/with-connection db-spec
   (sql/insert-record :product prod-12345))

但是,status是一个枚举,因此您无法将其作为普通字符串插入,而不将其转换为枚举:

'InStock'::product_status

我知道你可以用一个准备好的声明来做,如:

INSERT INTO product (name,status) VALUES (?,?::product_status)

但是,在没有使用准备好的声明的情况下,是否有办法呢?

解决方法

我今天使用stringtype = unspecified hack解决方法得到了这个工作.

您可以将此参数添加到db-spec中,如下所示:

(def db-spec {:classname "org.postgresql.Driver"
              :subprotocol "postgresql"
              :subname "//myserver:5432/mydatabase"
              :user "myuser"
              :password "mypassword"
              :stringtype "unspecified"}) ; HACK to support enums

然后只需使用insert!照常.

有一个解决方案不会削弱类型安全性是很好的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读