我有这个gorm片段,我试图写入/读取数据到DB
主要功能package main
import "studentDetails/gomodule/database"
// Connecting to database
if err := database.Open(); err != nil {
fmt.Println("Unable to connect to DB", err)
}
fmt.Println("Connected to DB !!!")
defer database.Close()
database.WriteToDB()
data := database.GetAllFromDB()
fmt.Println("Data from DB", data)
数据库功能package database
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
var DB *gorm.DB
type Student struct {
Id string `gorm:"type:varchar;primary_key;" json:"student_id"`
Name string `gorm:"type:varchar" json:"name"`
PhoneNumber int `gorm:"type:varchar" json:"phone_number"`
EmailId string `gorm:"type:varchar" json:"email_id"`
Branch string `gorm:"type:varchar" json:"branch"`
}
func Open() error {
var err error
DB, err = gorm.Open("postgres", "host=127.0.0.1 port=5433 user=postgres dbname=student password=postgres sslmode=disable")
if err != nil {
return err
}
return nil
}
func Close() error {
return DB.Close()
}
func WriteToDB() {
tempMap := Student{Branch: "ISE", EmailId: "chetan@gmail.com", Id: "1234", Name: "Chetan", PhoneNumber: 123456}
result := DB.Model(&Student{}).Create(tempMap)
fmt.Println("Data written in the database", result)
}
func GetAllFromDB() *gorm.DB {
st := Student{}
result := DB.Find(&st)
return result
}
当我执行程序时,我确实看到数据库正在连接。但出于某种原因,我不能读/写数据到表中(它确实说记录更新,但它没有)。我还尝试手动插入带有值的表,以检查get调用是否有效。下面是输出:
Connected to DB !!!
Data written in the database &{{{0 0} 0 0 0 0} {1234 Chetan 123456 chetan@gmail.com ISE} using unaddressable value 0 0xc000088000 false 0 {0xc000113db0} 0xc0000d4160 {{0 0} {{map[gorm:started_transaction0xc00042e0780xc0001781c0:0xc00042e080] false}} map[] 0} 0xc0000b8270 <nil> 0xc000099120 false <nil>}
Data from DB &{{{0 0} 0 0 0 0} 0xc0000b7950 <nil> 1 0xc000088000 false 0 {0xc000113db0} 0xc0000d4840 {{0 0} {<nil>} map[] 0} 0xc0000b8270 <nil> 0xc000099600 false <nil>}
有人能帮我指出我所犯的错误吗?谢谢。首先尝试导入gorm postgres驱动程序,以防止用字符串硬编码大量配置import "gorm.io/driver/postgres"
func Open() error {
var err error
connStr := "host=127.0.0.1 port=5433 user=postgres dbname=student password=postgres sslmode=disable"
DB, err = gorm.Open(postgres.Open(connStr), &gorm.Config{})
if err != nil {
return err
}
return nil
}
将WriteToDB修改如下
func WriteToDB() {
tempMap := Student{Branch: "ISE", EmailId: "chetan@gmail.com", Id: "1234", Name: "Chetan", PhoneNumber: 123456}
result := DB.Model(&Student{}).Create(&tempMap)
fmt.Println("Data written in the database", result)
}
Create()
函数应该有一个你想要持久化到数据库的对象的指针。
然而,我建议用这个替换整行result := DB.Create(&tempMap)
代替Calling DB.Model(<pointer>).Create(<pointer>)