Is it possible to patch load SQL statements from a

2019-05-16 09:44发布

问题:

I need to be able to load and execute a file with multiple SQL statements in clojure. For example, lets say I have a file with statements like:

ALTER TABLE bla...;
ALTER TABLE foo...;
UPDATE bla SET ...;
UPDATE foo SET ...;
ALTER TABLE bla DROP...;
ALTER TABLE foo DROP...;

You get the idea-- a file with many statements that are semicolon terminated.

I'm currently getting the following error when trying to use do-commands:

PSQLException org.postgresql.util.PSQLException: Too many update results were returned.

回答1:

The way I ended up solving this was like so:

(ns myns.db
  (:require [clojure.java.jdbc :as sql]            
            [clojure.java.io :refer [resource]]))

(defn db-conn [] ...)

(defn exec-sql-file  
   [file]  
   (sql/with-connection (db-conn)
    (sql/do-prepared
      (slurp (resource file)))))

...

; from your lein project where src/sql/some-statements.sql is the file you want to load
(exec-sql-file "sql/some-statements.sql")

I would be interested to hear how others have handled this problem. Is there a better way?