patterngoMinor
Go database helper code
Viewed 0 times
databasecodehelper
Problem
Today I've implemented a database helper in Go. I'm new in Go world so I just wanted someone with more experience to take a look and tell me what is good and especially, what is bad (and why, if possible).
This code works and I am able to use it in the main package, for example, using
package clinic
import (
"fmt"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
)
func init() {
orm.RegisterDriver("mysql", orm.DR_MySQL)
orm.RegisterDataBase("default", "mysql", "user@pass/db-name?charset=utf8")
}
func NewPet(pet *Pet){
id, err := orm.NewOrm().Insert(pet)
if err == nil {
fmt.Println(id)
}
}
func UpdatePet(pet *Pet){
if num, err := orm.NewOrm().Update(pet); err == nil {
fmt.Println(num)
}
}
func DeletePet(pet *Pet){
if num, err := orm.NewOrm().Delete(pet); err == nil {
fmt.Println(num)
}
}
func AllPets() []interface{} {
var pets []Pet
all, err := orm.NewOrm().QueryTable("pet").All(&pets)
fmt.Printf("Returned Rows Num: %s, %s", all, err)
result := make([]interface{}, len(pets))
for i, s := range pets {
r := s;
result[i] = &r
}
return result;
}This code works and I am able to use it in the main package, for example, using
clinic.NewPet(&Pet{field: "value"}). I am just wondering if this can be improved.Solution
What do you think about error handling? I think that's good idea to provide some log messages for main operation with db (CRUD).
As example for Delete function:
As example for Delete function:
func DeletePet(pet *Pet) {
num, err := orm.NewOrm().Delete(pet)
if err != nil {
log.Println("DELETE", err)
} else {
fmt.Println(num)
}
}Code Snippets
func DeletePet(pet *Pet) {
num, err := orm.NewOrm().Delete(pet)
if err != nil {
log.Println("DELETE", err)
} else {
fmt.Println(num)
}
}Context
StackExchange Code Review Q#114378, answer score: 2
Revisions (0)
No revisions yet.