【问题标题】:How to disconnect Postgrex connection?如何断开 Postgrex 连接?
【发布时间】:2017-06-22 14:31:07
【问题描述】:

我试图弄清楚如何连接到 postgres 数据库、运行查询,然后断开连接。

查看Postgrex,我使用建立连接

{:ok, pid} = Postgrex.start_link(hostname: "localhost", username: "postgres", password: "postgres", database: "postgres")

然后我使用

执行我的查询
Postgrex.query!(pid, "SELECT user_id, text FROM comments", [])

但是,我该如何断开连接呢?

我想断开连接,因为我正在循环访问 N 个数据库并对所有数据库运行相同的查询。

我尝试退出进程,例如Process.exit(pid, :bye),但它也终止了生成过程,因为它是从 start_link/3 开始的。我在Postgrex 中找不到start/3 函数。

【问题讨论】:

    标签: postgresql elixir phoenix-framework ecto postgrex


    【解决方案1】:

    由于Postgrex.start_link返回的pidGenServer,所以可以使用GenServer.stop/1

    iex(1)> {:ok, pid} = Postgrex.start_link(hostname: "localhost", username: "postgres", password: "postgres", database: "postgres")
    {:ok, #PID<0.277.0>}
    iex(2)> GenServer.stop(pid)                                                                                                 
    :ok
    iex(3)> GenServer.stop(pid)
    ** (exit) no process: the process is not alive or there's no process currently associated with the given name, possibly because its application isn't started
        (stdlib) proc_lib.erl:797: :proc_lib.stop/3
    

    【讨论】:

    • 谢谢!以这种方式依赖 postgrex 的实现细节有什么危险吗?
    • 基于文档,它使用DBConnection,而DBConnection 本身使用GenServer。因此可以肯定地说,该文档暗示它使用了GenServer,从而使GenServer.stop/1 调用的使用安全。
    猜你喜欢
    • 1970-01-01
    • 2011-02-03
    • 2012-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-15
    • 2015-05-01
    相关资源
    最近更新 更多