日期:2014-05-16  浏览次数:20413 次

Golang(7)Database Layer

Golang(7)Database Layer

5.1 database/sql Interface
sql.Register
Register(name string, driver driver.Driver) register the driver you add to the golang system.

https://github.com/mattn/go-sqlite3

func init() {
? ? ?sql.Register(“sqlite3”, &SQLiteDriver{})
}

https://github.com/mikespook/mymysql

var d = Driver{proto: “tcp”, raddr: “127.0.0.1:3306” }
func init() {
? ? ?Register(“SET NAMES utf8”)
? ? ?sql.Register(“mymysql”, &d)
}

For example
import (
? ? ?“database/sql”
? ? ?_ “github.com/mattn/go-sqlite3"
)

If we import this package, it will automatically call the init method in that package.

driver.Driver
type Driver interface {
? ? ?Open(name string) (Conn, error)
}
The name parameter will be used to retrieve the database connection info.
We can use this Conn to do one go routine execution, but you can not use it twice.

driver.Conn
type Conn interface {
? ? ?Prepare(query string) (Stmt, error)
? ? ?Close() error
? ? ?Begin() (Tx, error)
}

Tx is