Golang與MySQL

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

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://godoc.org/

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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.