Skip to content

Instantly share code, notes, and snippets.

@giwa giwa/file0.go
Created Apr 26, 2016

Embed
What would you like to do?
dbr: simple orm for golang ref: http://qiita.com/giwa/items/1837cc5d78644f2a1736
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
"github.com/gocraft/dbr"
)
const (
mysqlDSN = "interop:interop@tcp(localhost:3306)/interop2016"
)
type DoorMeta struct {
Id int64 `db:"id"`
Name string `db:"name"`
Value string `db: "value"`
CreatedAt dbr.NullTime `db: "created_at"`
}
func main() {
var result sql.Result
var err error
// Open connection
conn, _ := dbr.Open("mysql", mysqlDSN, nil)
// Create session
sess := conn.NewSession(nil)
// Insert
result, err = sess.InsertInto("door_meta").
Columns("name", "value").
Values("foo2", "bar").
Exec()
if err != nil {
log.Fatal(err)
} else {
count, _ := result.RowsAffected()
fmt.Println(count)
}
// Insert with struct
meta := &DoorMeta{Name: "foofoo", Value: "barbar"}
sess.InsertInto("door_meta").
Columns("name", "value").
Record(meta). // Watch out! this is not Values
Exec()
// Select
var m []DoorMeta
sess.Select("*").From("door_meta").Load(&m)
fmt.Println(m)
// Update
result, err = sess.Update("door_meta").
Set("name", "giwa").
Where("name = ?", "foo").
Exec()
if err != nil {
log.Fatal(err)
} else {
count, _ := result.RowsAffected()
fmt.Println(count)
}
fmt.Println(m[0].CreatedAt.Time)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.