go - 如何在 Buffalo 中执行原始 SQL?

标签 go buffalo

如何在 Buffalo 中执行原始 SQL 查询,而不必使用 sqlx 建立自己的数据库连接?

澄清一下:我database.yml 中定义了我的数据库连接,但此时我不想使用 Pop 模型。

最佳答案

您还可以使用 Pop 定义 RawQueries:https://godoc.org/github.com/gobuffalo/pop#Connection.RawQuery

在你的 Buffalo Action 中你可以做这样的事情:

func (v myResource) MyMethod(c buffalo.Context) error {
    // Get the DB connection from the context
    tx, ok := c.Value("tx").(*pop.Connection) // you get your connection here
    if !ok {
        return errors.WithStack(errors.New("no transaction found"))
    }
    q := tx.RawQuery("select * from foo where id = ?", 1) // you make your query here
    if err := q.All(model); err != nil {
        return errors.WithStack(err)
    }
}

这将是使用 Pop 而不是预定义模型的解决方案。在那种情况下,您只需使用 Buffalo 上下文附带的连接。

关于go - 如何在 Buffalo 中执行原始 SQL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51772322/

相关文章:

mongodb - UpdateOne、ReplaceOne、FindOneAndReplace - 模式匹配,但没有更新数据

go - 系统休眠后 time.Time.Sub() 计算错误

postgresql - 如何使 Buffalo 事务中间件提交?

go - 带“--skip-model”标志的“Generate resource”命令导致资源错误

go - 如何连接字符串数组?

go - 在 Buffalo 中集成 Sentry 和 Elastic APM

go - 修改原生 Golang 包后如何重建它们?

string - 从字符串中获取整数月份值

sockets - golang阅读了许多websockets

go - 如何遍历请求参数