go - 如何在 Buffalo 中执行原始 SQL?
问题描述
如何在Buffalo中执行原始 SQL 查询,而无需设置我自己的数据库连接sqlx
?
澄清一下:我在中定义了我的数据库连接database.yml
,但此时我不想使用 Pop 模型。
解决方案
您还可以使用 Pop 定义 RawQueries:https ://godoc.org/github.com/gobuffalo/pop#Connection.RawQuery
在您的 Buffalo 操作中,您可以执行以下操作:
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 上下文附带的连接。
推荐阅读
- ionic-framework - 离子如何禁用滑动屏幕上的滑动?
- flutter - Flutter:有条件的底部导航栏,根据if条件显示页面
- android - 如何在 Android 中制作像 Skype 一样的 Listview。更改适配器中的对象设计运行时。(请检查屏幕截图)
- selenium-webdriver - Selenium下的ChromeDriver 79每次都需要手动接受HTTPS证书
- c# - 使用未声明的参数数量实现查询功能?
- python - 如何平衡python中的训练集?
- django - 如何添加到购物车 drf
- javascript - 日期/时间时钟脚本不支持字体设置
- kubernetes - http 请求总是在 k8s 集群 pod 的容器中被阻塞
- ios - 委托函数在删除 CollectionView 项目 Swift 时无法正确调用