jke*_*one 5 sql postgresql go go-gorm
我正在运行一个查询来检查表是否存在或不使用 golang 的 gorm orm 。下面是我的代码。
package main
import (
"fmt"
"log"
"gorm.io/driver/postgres"
"gorm.io/gorm"
_ "github.com/lib/pq"
)
// App sets up and runs the app
type App struct {
DB *gorm.DB
}
`const tableCreationQuery = `SELECT count (*)
FROM information_schema.TABLES
WHERE (TABLE_SCHEMA = 'api_test') AND (TABLE_NAME = 'Users')`
func ensureTableExists() {
if err := a.DB.Exec(tableCreationQuery); err != nil {
log.Fatal(err)
}
}`
Run Code Online (Sandbox Code Playgroud)
预期的响应应该是 1 或 0。我从另一个 SO 答案中得到了这个。相反我得到这个
2020/09/03 00:27:18 &{0xc000148900 1 0xc000119ba0 0} 退出状态 1 失败 go-auth 0.287s
我未经训练的头脑说它是一个指针,但我如何引用返回的值来确定其中包含的内容?
小智 4
如果你想检查你的 SQL 语句是否在 GORM 中成功执行,你可以使用以下命令:
tx := DB.Exec(sqlStr, args...)
if tx.Error != nil {
return false
}
return true
Run Code Online (Sandbox Code Playgroud)
但是,在您的示例中使用 SELECT 语句,然后您需要检查结果,这将更适合使用 DB.Raw() 方法,如下所示
var exists bool
DB.Raw(sqlStr).Row().Scan(&exists)
return exists
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33586 次 |
| 最近记录: |