1. 在golib下载go-sql-driver/mysql
go get github.com/go-sql-driver/mysql
2. 代码引入
import (
"database/sql"
"github.com/go-sql-driver/mysql"
)
3. 创建DB?
db, err := sql.Open("mysql", "user:password@/dbname")
注意: sql.DB是封装driver包提供高级API, 提供了安全,多连接的操作.
4. 文档:
http://godoc.org/github.com/go-sql-driver/mysql
http://localhost:8080/pkg/database/sql/#DB
5. 总结:
database/sql的主要interface
sql.Register{
unc Register(name string, driver driver.Driver) error
}
database/sql/driver的主要interface
type Driver interface {
Open(name string) (Conn, error)
}
type Conn interface { Prepare(query string) (Stmt, error) Close() error Begin() (Tx, error)}
type Stmt interface { Close() error NumInput() int Exec(args []Value) (Result, error) Query(args []Value) (Rows, error)}
type Tx interface { Commit() error Rollback() error}type Result interface { LastInsertId() (int64, error) RowsAffected() (int64,error)}type Rows interface { Columns() []string Close() error Next(dest []Value) error}type Execer type Value type ValueConverter type Valuer
但database/sql定义更高级的API: sql.DB, 是多并发可重用.type DB func Open(driverName, dataSourceName string) (*DB, error) func (db *DB) Begin() (*Tx, error) func (db *DB) Close() error func (db *DB) Driver() driver.Driver func (db *DB) Exec(query string, args ...interface{}) (Result, error) func (db *DB) Ping() error func (db *DB) Prepare(query string) (*Stmt, error) func (db *DB) Query(query string, args ...interface{}) (*Rows, error) func (db *DB) QueryRow(query string, args ...interface{}) *Row func (db *DB) SetMaxIdleConns(n int) func (db *DB) SetMaxOpenConns(n int)