如何断开Postgrex连接?

Jes*_*ieh 2 postgresql elixir ecto phoenix-framework postgrex

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

看看Postgrex,我建立了一个连接

{:ok, pid} = Postgrex.start_link(hostname: "localhost", username: "postgres", password: "postgres", database: "postgres")
Run Code Online (Sandbox Code Playgroud)

然后我使用执行我的查询

Postgrex.query!(pid, "SELECT user_id, text FROM comments", [])
Run Code Online (Sandbox Code Playgroud)

但是,我怎么断开?

我想断开连接,因为我循环遍历N个数据库并对所有数据库运行相同的查询.

我尝试退出过程,例如Process.exit(pid, :bye),但它也因为它的开始而杀死了产卵过程start_link/3.我找不到一个start/3功能Postgrex.

Dog*_*ert 7

由于pid返回的Postgrex.start_link是a GenServer,您可以使用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
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!以这种方式依赖 postgrex 的实现细节有什么危险吗? (2认同)