如何从 clojure.java.jdbc 删除或创建数据库?
我想从 clojure.java.jdbc 创建/删除数据库。这会失败:
(require '[clojure.java.jdbc :as sql])
(def db
{:classname "org.postgresql.Driver"
:subprotocol "postgresql"
:subname "//localhost/postgres"
:user "postgres"})
(defn drop-database [name]
(sql/do-commands (str "drop database " name)))
(sql/with-connection db
(drop-database "db_name"))
因为 do-commands 启动一个事务,并且显然您无法在事务内删除或创建数据库。有什么想法吗?
谢谢!
I would like to create/drop a database from clojure.java.jdbc. This fails:
(require '[clojure.java.jdbc :as sql])
(def db
{:classname "org.postgresql.Driver"
:subprotocol "postgresql"
:subname "//localhost/postgres"
:user "postgres"})
(defn drop-database [name]
(sql/do-commands (str "drop database " name)))
(sql/with-connection db
(drop-database "db_name"))
because do-commands starts a transaction, and apparently you can't drop or create databases inside a transaction. Any ideas?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
获取
do-commands
的源代码(此处)并删除对transaction
的调用:Take the source for
do-commands
(here) and remove the call totransaction
:无事务执行功能被整合到 db-do-commands 中。
现在这个稍微简单的版本正在工作:
如果您没有指定 false 作为第二个参数,它将无法工作,因为它将尝试启动事务。
The transactionless execution functionality was rolled into
db-do-commands
.Now this slightly simpler version is working:
If you don't specify false as the second argument, it won't work as it will attempt to start a transaction.
对于较新的 clojure 版本,建议的方法不再有效。我成功地使用了这个功能:
With newer clojure versions, the suggested approach no longer works. I was successful with this function:
这是唯一对我有用的解决方案
(defn create-database [name]
(println {:connection-uri (db-jdbc-uri :数据库名称 "")})
(jdbc/with-db-connection [conn {:connection-uri (db-jdbc-uri :数据库名称 "")}]
(jdbc/db-do-commands conn false (str "CREATE DATABASE " name))))
基本上,您需要在不提供数据库或连接到其他数据库(不是您要删除的数据库)的情况下进行连接
这将得到转换为此代码。
This is the only solution that worked for me
(defn create-database [name]
(println {:connection-uri (db-jdbc-uri :database-name "")})
(jdbc/with-db-connection [conn {:connection-uri (db-jdbc-uri :database-name "")}]
(jdbc/db-do-commands conn false (str "CREATE DATABASE " name))))
Basically you need to connect without providing a database or connecting to a different database (not the one you are deleting)
This will get transilated to this code.