Using the clojure jdbc library with postgresql. I have a table “xxx” with a timestamp column “created_at” in postgresql, and I have a string containing a date in the right format. Doing an insert fails:
(require '[clojure.java.jdbc :as sql])
(sql/with-connection *db*
(sql/insert-record :xxx {:created_at "Thu Feb 09 10:38:01 +0000 2012"}))
Here is the error:
org.postgresql.util.PSQLException: ERROR: column "created_at"
is of type timestamp with time zone but expression is of type character varying
So I understand that postgres requires a timestamp value, but how do I convert my string representation of the date into something postgres will accept? java.util.Date fails also, and I can’t find any docs on the clojure postgres library.
Thanks!
You’ll need to pass in a
java.sql.Timestampinstance. To parse your string into one usingclj-time, a Joda-Time-wrapping library for Clojure, you’d do something along the following lines:The returned value can then be passed to PostgreSQL via JDBC.
In case you’re obtaining the date in some other string format and converting it to this one, you could skip the conversion and provide an appropriate formatter for the original representation. There are quite a few available by default in the
clj-time.format/formattersmap, say(clj-time.format/show-formatters)at the REPL to see a list with examples. Also,clj-time.coerce/from-stringtries all default formatters in sequence returning the value of the first succeeding parse (nilif there is none). If you’re obtaining the date as ajava.util.Dateor along, seefrom-dateandfrom-longin the same namespace.Use
[clj-time "0.3.6"]as the dependency specifier in yourproject.cljif you decide to useclj-time.Alternatively, you could use some other way of parsing your timestamp string into a
java.sql.Timestamp;Timestampitself can parse a different string representation:clj-timeis the most sane way of dealing with date and time in Clojure, though, so it’s likely to be worth your while.