创建DB连接

创建DB对象

  • mysql驱动

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

db,err:=sql.Open("mysql",Username+":"+PassWord+"@tcp(localhost:3306)/"+dbname+"?charset=utf8")

  • sqlite驱动

import (
    _ "github.com/mattn/go-sqlite3"
    "database/sql"
)

db, err := sql.Open("sqlite3", "./asta.db")

  • SQL server驱动

    go get github.com/denisenkom/go-mssqldb


import (
    "database/sql"
    _ "github.com/denisenkom/go-mssqldb"
)

connString := fmt.Sprintf("server=%s;user id=%s;password=%s;port=%d", *server, *user, *password, *port)

conn, err := sql.Open("mssql", connString)

  • oracle驱动

    go get gopkg.in/rana/ora.v3


import (
    "database/sql"
    "fmt"
    _ "github.com/mattn/go-oci8"
    "os"
    "strings"
)

func getDSN() string {
    var dsn string
    if len(os.Args) > 1 {
        dsn = os.Args[1]
        if dsn != "" {
            return dsn
        }
    }
    dsn = os.Getenv("GO_OCI8_CONNECT_STRING")
    if dsn != "" {
        return dsn
    }
    fmt.Fprintln(os.Stderr, `Please specifiy connection parameter in GO_OCI8_CONNECT_STRING environment variable,
or as the first argument! (The format is user/name@host:port/sid)`)
    return "scott/tiger@XE"
}

sql.Open("oci8", getDSN())
  • mongodb驱动

    go get gopkg.in/mgo.v2

你可能感兴趣的:(创建DB连接)