带有Ecto的原始SQL [英] Raw SQL with Ecto

查看:53
本文介绍了带有Ecto的原始SQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Elixir和Phoenix Framework领域,我是一个新手.我正在尝试遵循TheFireHoseProject教程,但是在使用Ecto查询原始SQL时遇到了问题.本教程说这应该可行:

I'm very new in the world of Elixir and Phoenix Framework. I'm trying to follow TheFireHoseProject tutorial, but having problems with querying raw SQL with Ecto. The tutorial says this should work:

defmodule Queries do
def random do
  query = Ecto.Adapters.Postgres.query(
    Repo,
    "SELECT id, saying, author from quotes ORDER BY RANDOM() LIMIT 1",
    [])
  %Postgrex.Result{rows: [row]} = query
  {id, saying, author} = row
  %Splurty.Quote{id: id, saying: saying, author: author}
end
end

我遇到了一个Ecto.Adapters.Postgres.query不存在的运行时错误(未定义函数).

I'm getting a runtime error that the Ecto.Adapters.Postgres.query doesn't exist (undefined function).

我尝试搜索Ecto文档,发现可能存在一个名为run_query的函数,但它也不起作用.

I tried to search the Ecto documentation and found that there might be a function called run_query, but it doesn't work either.

我认为我正在使用Ecto 1.1.4,但没有找到任何好的(最新的)样本来说明如何使用Ecto查询原始SQL.

I think I'm using Ecto 1.1.4 and I didn't find any good (up-to-date) samples of how can I query raw SQL with Ecto.

firehoseproject的链接为: http://phoenix.thefirehoseproject.com/

The link to the firehoseproject is: http://phoenix.thefirehoseproject.com/

推荐答案

alias Ecto.Adapters.SQL

querystring = "..."

result = SQL.query(Repo, querystring , [])

然后您可以将结果添加到这样的列表中:

And then you can add the result to a list for example like this:

list = []

case result do
  {:ok, columns} ->
            list = for item <- columns.rows do
                List.first(item)
            end
  _ -> IO.puts("error")
end

这篇关于带有Ecto的原始SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆