如何断开Postgrex连接?

时间:2017-06-22 14:31:08

标签: postgresql elixir phoenix-framework ecto postgrex

我试图弄清楚如何连接到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。我无法在start/3中找到Postgrex函数。

1 个答案:

答案 0 :(得分:7)

pid返回的Postgrex.start_linkGenServer,您可以使用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