无法使用 Golang 从 SQL Server 查询数据 - 出现错误“无效的对象名称”

我正在尝试使用 Golang 和 GORM 从 SQL Server 查询数据。但我收到以下错误:-


DB Connection: &{{{0 0} 0 0 0 0} <nil> <nil> 0 0xc0000a4480 false 0 {0xc0000e5db0} <nil> {{0 0} {<nil>} map[] 0} 0xc00004c5b0 0xaccbe0 0xc00014d0a0 false <nil>}


HasTable- Currency: true

{CurrencyId:0 Code: Description:}


[35m(C:/Users/RahulBFL/Documents/architechbc/dot net/GORM/main.go:26)[0m

[33m[2019-12-27 15:56:13][0m [31;1m mssql: Invalid object name 'currencies'. [0m

我的表架构如下所示:-


     Currency

CurrencyId    int

Code          char

Description   varchar

在 SSMS 上,我可以使用以下命令成功查询表


select * from IMBookingApp.dbo.Currency

我的 Golang 代码


package main


import (

    "fmt"

    "github.com/jinzhu/gorm"

    _ "github.com/jinzhu/gorm/dialects/mssql"

)


type Currency struct {

    CurrencyId  int

    Code        string

    Description string

}


func main() {


    db, err := gorm.Open("mssql", "sqlserver://USERNAME:PASSWORD@Endpoint:1433?database=DATABASENAME&Initial+Catalog=SCHEMA_NAME")


    if err != nil {

        fmt.Println("Connection Error:", err)

    }


   fmt.Println("DB Connection", db)



    fmt.Println("HasTable- Currency:", db.HasTable("ClientUser"))


    var Currency Currency

    db.Find(&Currency)


    fmt.Printf("%+v\n", Currency)


    defer db.Close()

}

我不明白为什么我收到错误 - 无效的对象名称“货币”。尽管架构中没有货币,但只有货币。


任何帮助将不胜感激。


守候你守候我
浏览 98回答 1
1回答

慕侠2389804

如果您检查错误,Invalid object name 'currencies'它会尝试查找名为 的表currencies。默认情况下,gorm 将表名称复数。如果您想要自定义表名称,可以如下定义:func (Currency) TableName() string {&nbsp; &nbsp; return "currency"}或者您可以使用以下命令全局禁用它:db.SingularTable(true)所以你的样本应该是这样的:type Currency struct {&nbsp; &nbsp; CurrencyId&nbsp; int&nbsp; &nbsp; Code&nbsp; &nbsp; &nbsp; &nbsp; string&nbsp; &nbsp; Description string&nbsp; &nbsp; CreateDate&nbsp; time.Time}func (Currency) TableName() string {&nbsp; &nbsp; return "currency"}func main() {&nbsp; &nbsp; db, err := gorm.Open("mssql", "sqls*******talog=dbo")&nbsp; &nbsp; db.SingularTable(true)&nbsp; &nbsp; fmt.Println("db.HasTable: Currency:", db.HasTable("ClientUser"))&nbsp; &nbsp; var Currency []Currency&nbsp;&nbsp; &nbsp; db.Find(&Currency)&nbsp; &nbsp; ....}
打开App,查看更多内容
随时随地看视频慕课网APP