Git Product home page Git Product logo

db's Introduction

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:hunter2@unix(/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

db's People

Contributors

guregu avatar

Stargazers

Ybb avatar

Watchers

Ybb avatar James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.