denisenkom / go-mssqldb

Microsoft SQL server driver written in go language
BSD 3-Clause "New" or "Revised" License
1.82k stars 500 forks source link

No required module provides package? The go.mod file not found in current directory or any parent directory; see 'go help modules'. #650

Closed sheeeng closed 3 years ago

sheeeng commented 3 years ago

If we encountered these messages, it is most likely we run go run commands outside of ${GOPATH}.

Issue

no required module provides package github.com/denisenkom/go-mssqldb: go.mod file not found in current directory or any parent directory; see 'go help modules'
package main

import (
        "context"
        "database/sql"
        "fmt"
        "log"
        "os"

        _ "github.com/denisenkom/go-mssqldb"
)

var db *sql.DB
var port = 1433

var server = os.Getenv("SQL_SERVER_NAME")
var user = os.Getenv("SQL_SERVER_USER_NAME")
var password = os.Getenv("SQL_SERVER_USER_PASSWORD")
var database = os.Getenv("SQL_DATABASE_NAME")

func main() {
        // Build connection string
        connString := fmt.Sprintf("server=%s;user id=%s;password=%s;port=%d;database=%s;",
                server, user, password, port, database)
        var err error
        // Create connection pool
        db, err = sql.Open("sqlserver", connString)
        if err != nil {
                log.Fatal("Error creating connection pool: ", err.Error())
        }
        ctx := context.Background()
        err = db.PingContext(ctx)
        if err != nil {
                log.Fatal(err.Error())
        }
        fmt.Printf("Connected!")
}
$ go version      
go version go1.16.3 darwin/amd64
$ go get -u -v github.com/denisenkom/go-mssqldb
$ ls ${GOPATH}/pkg/mod/github.com/denisenkom/go-mssqldb@v0.9.0/README.md
/Users/USERNAME/go/pkg/mod/github.com/denisenkom/go-mssqldb@v0.9.0/README.md
$ go build main.go               
main.go:10:2: no required module provides package github.com/denisenkom/go-mssqldb: go.mod file not found in current directory or any parent directory; see 'go help modules'
$ go run main.go  
main.go:10:2: no required module provides package github.com/denisenkom/go-mssqldb: go.mod file not found in current directory or any parent directory; see 'go help modules'

Solution

We must run go run command exactly inside ${GOPATH}/src/.../.../... directory.

For example, ${GOPATH}/src/github.com/USERNAME/sqltest-example.

$ pwd
/Users/USERNAME/go/src/mod/github.com/USERNAME/sqltest-example
$ go get -u -v github.com/denisenkom/go-mssqldb
$ ls main.go
main.go
$ go run main.go
Connected!%
sheeeng commented 3 years ago

Closing this issue as it is written for references.