Clojure contrib sql 使所有数字成为 BigDecimal

发布于 2024-09-19 15:16:23 字数 411 浏览 7 评论 0原文

clojure.contrib.sql 库为所有数字字段返回 BigDecimals。将某些字段设置为整数的好方法是什么?示例代码如下:

(sql/with-connection my-db 
   (sql/with-query-results res 
      [sql-str 6722] 
      (into [] res)))

在生成的记录集合中,所有数字均为 BigDecimal。其中一些是外键,出于我自己的原因,我需要它们是整数。

我知道我可以迭代集合并转换它们,但我宁愿不这样做,因为它是一个非常大的集合,并且如果数字适合整数,则让库使用 ResultsSet.getInteger 似乎是正确的。

DB是Oracle,整数DB字段定义为NUMBER(10)

谢谢

The clojure.contrib.sql library returns BigDecimals for all numeric fields. What's a good way to have some fields as Integers? Example code below:

(sql/with-connection my-db 
   (sql/with-query-results res 
      [sql-str 6722] 
      (into [] res)))

In the resulting collection of records all numbers are BigDecimal. Some of these are foreign keys, and for reasons of my own, I need them to be integer.

I know I can iterate over the collection and convert them, but I would rather not do this as it is a very large collection, and it seems right to have the library use ResultsSet.getInteger if the number fits into an integer.

The DB is Oracle, and the integer DB fields are defined as NUMBER(10)

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

落花浅忆 2024-09-26 15:16:23

正如 atreyu 所指出的,10 位整数不一定适合 Integer

更重要的是,您给出的 seq 是由 clojure.core/resultset-seq 创建的,而 clojure.core/resultset-seq 又调用 ResultSet.getObject(int)。根据 JDBC 规范,将返回 BigDecimals,因为它是与列的 SQL 类型相对应的 java 类型。

另外,您无需担心“迭代集合”。 resultset-seq 是惰性的,而 map 是惰性的,因此您最终只需在使用每个数字之前就对其进行转换。例如,

(sql/with-connection my-db 
   (sql/with-query-results res 
      [sql-str 6722] 
      (do-stuff 
         (map (comp int :id) res))))

As atreyu noted, a 10-digit integer won't necessarily fit within an Integer.

More importantly, the seq you are given is created by clojure.core/resultset-seq, which in turn is calling ResultSet.getObject(int). As per the JDBC spec, the BigDecimals are being returned because that's the java type that corresponds to the column's SQL type.

Also, you don't need to worry about "iterat[ing] over the collection". The resultset-seq is lazy, and map is lazy, so you'll just end up converting each number right before you consume them. E.g.,

(sql/with-connection my-db 
   (sql/with-query-results res 
      [sql-str 6722] 
      (do-stuff 
         (map (comp int :id) res))))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文