Clojure/JDBC/Postgresql:我试图从字符串更新postgresql中的时间戳值,得到一个错误

pri*_*ing 14 postgresql timestamp jdbc clojure

将clojure jdbc库与postgresql一起使用.我在postgresql中有一个带有时间戳列"created_at"的表"xxx",我有一个包含正确格式的日期的字符串.执行插入失败:

(require '[clojure.java.jdbc :as sql])

(sql/with-connection *db*
  (sql/insert-record :xxx {:created_at "Thu Feb 09 10:38:01 +0000 2012"}))
Run Code Online (Sandbox Code Playgroud)

这是错误:

org.postgresql.util.PSQLException: ERROR: column "created_at" 
is of type timestamp with time zone but expression is of type character varying
Run Code Online (Sandbox Code Playgroud)

所以我理解postgres需要一个时间戳值,但是如何将我的日期字符串表示转换为postgres会接受的内容?java.util.Date也失败了,我在clojure postgres库上找不到任何文档.

谢谢!

Mic*_*zyk 17

你需要传入一个java.sql.Timestamp实例.要使用Clojure clj-timeJoda-Time -wrapping库将您的字符串解析为一个字符串,您可以执行以下操作:

(require '(clj-time [format :as timef] [coerce :as timec])

(->> "Thu Feb 09 10:38:01 +0000 2012"
     (timef/parse (timef/formatter "EEE MMM dd HH:mm:ss Z yyyy"))
     timec/to-timestamp)
Run Code Online (Sandbox Code Playgroud)

然后可以通过JDBC将返回的值传递给PostgreSQL.

如果您以其他字符串格式获取日期并将其转换为此日期,则可以跳过转换并为原始表示提供适当的格式化程序.默认情况下,clj-time.format/formatters地图中有很多可用,例如(clj-time.format/show-formatters)在REPL中查看带有示例的列表.此外,clj-time.coerce/from-string按顺序尝试所有默认格式化程序,返回第一个后续解析的值(nil如果没有).如果您将日期作为a java.util.Date或a 获取long,请参阅from-datefrom-long在同一名称空间中.

使用[clj-time "0.3.6"]在你的依赖符project.clj,如果你决定使用clj-time.

或者,您可以使用其他方式将时间戳字符串解析为java.sql.Timestamp; Timestamp本身可以解析不同的字符串表示:

(java.sql.Timestamp/valueOf "2004-10-19 10:23:54")
Run Code Online (Sandbox Code Playgroud)

clj-time 然而,在Clojure中处理日期和时间是最理智的方式,所以它很可能值得你花时间.

  • 由于这是一个旧答案,而且我是 clj-time 的维护者之一,因此我会注意到 clj-time 已弃用,我们鼓励人们迁移到 Java Time(从 Java 8 开始内置)或一个它的包装器库 - 根据 clj-time 的自述文件! (2认同)