memo
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)
}