All Projects → guregu → Db

guregu / Db

Licence: bsd-2-clause
shove database connections in your context

Programming Languages

go
31211 projects - #10 most used programming language

db GoDoc

import "github.com/guregu/db"

db is a simple helper for using x/net/context with various databases. With db you can give each of your connections a name and shove it in your context. Later you can use that name to retrieve the connection. Feel free to fork this and add your favorite drivers.

Example

First we make a context with our DB connection. Then we use kami to set up a web server and pass that context to every request. From within the request, we retrieve the DB connection and send a query.

package main

import (
	"fmt"
	"net/http"

	"github.com/guregu/db"
	"github.com/guregu/kami"
	"golang.org/x/net/context"

	_ "github.com/go-sql-driver/mysql"
)

func main() {
	ctx := context.Background()
	ctx = db.OpenSQL(ctx, "main", "mysql", "root:[email protected](/tmp/mysql.sock)/myCoolDB")
	defer db.Close(ctx) // closes all DB connections
	kami.Context = ctx

	kami.Get("/hello/:name", hello)
	kami.Serve()
}

func hello(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	mainDB := db.SQL(ctx, "main") // *sql.DB
	var greeting string
	mainDB.QueryRow("SELECT content FROM greetings WHERE name = ?", kami.Param(ctx, "name")).Scan(&greeting)
	fmt.Fprint(w, greeting)
}

License

BSD

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].