6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

dbr: simple orm for golang

Posted at

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

6
6
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?