Upgrade to Pro — share decks privately, control downloads, hide ads and more …

いまさらdatabase/sql / 2018-12-18

rock619
December 18, 2018

いまさらdatabase/sql / 2018-12-18

golang.tokyo #20

rock619

December 18, 2018
Tweet

Other Decks in Technology

Transcript

  1. DB 接続 DB 接続 import ( "database/sql" _ "github.com/go-sql-driver/mysql" )

    func main() { db, err := sql.Open("mysql", "user:password@protocol(host: if err != nil { panic(err) } defer db.Close() }
  2. database driver の import database driver の import database/sql/driver パッケージ

    database driver のinterface が定義されている 使用するdriver のimport driver のinterface の実装 github.com/go-sql-driver/mysql/
  3. QueryRow() QueryRow() var name string err = db.QueryRow("select name from

    users where id = ?", 1).Sc if err != nil { return err } fmt.Println(name)
  4. QueryRow() QueryRow() var name string err = db.QueryRow("select name from

    users where id = ?", 1).Sc switch err { case sql.ErrNoRows: return "" case nil: return name default: return err }
  5. Null Null type NullString struct { String string Valid bool

    // Valid is true if String is not NULL }
  6. Scanner Scanner // Scan implements the Scanner interface. func (ns

    *NullString) Scan(value interface{}) error { if value == nil { ns.String, ns.Valid = "", false return nil } ns.Valid = true return convertAssign(&ns.String, value) }
  7. Valuer Valuer // Value implements the driver Valuer interface. func

    (ns NullString) Value() (driver.Value, error) { if !ns.Valid { return nil, nil } return ns.String, nil }