Golang Sql.Open undefined (type string has no field or method Open)

Golang Sql.Open undefined (type string has no field or method Open)

我在下面的代码中给出了 sql.Open 行中的未定义错误。不确定如何修复此错误。

有解决此错误的帮助吗?

79:16 sql.Open undefined (type string has no field or method Open) Process exiting with code: 2 signal: false

package main

import (
    "database/sql"
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "path/filepath"
    "runtime"
    "sort"
    "strings"

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

const (
    username = ""
    password = ""
    hostname = ""
    dbname   = ""
)

type Server struct {
    ID          int
    Servername  string
    IP          sql.NullString `json:"ip"`
    OS          sql.NullString `json:"os"`
}

func dsn(dbName string) string {
    return fmt.Sprintf("%s:%s@tcp(%s)/%s", username, password, hostname, dbName)
}

func RemoveDuplicates(xs *[]string) {
    found := make(map[string]bool)
    j := 0
    for i, x := range *xs {
        if !found[x] {
            found[x] = true
            (*xs)[j] = (*xs)[i]
            j++
        }
    }
    *xs = (*xs)[:j]
}

func main() {
    var TEMPDIR = os.Getenv("HOME")
    if runtime.GOOS == "windows" {
        TEMPDIR = "c:\temp"
    }
    filename := filepath.FromSlash(TEMPDIR + "/a.txt")
    content, err := ioutil.ReadFile(filename)
    if err != nil {
        log.Fatal(err)
    }

    text := string(content)
    fmt.Println(text)

    w := strings.Fields(text)
    RemoveDuplicates(&w)
    sort.Strings(w)
    j := strings.Join(w, "','")
    result := "('" + j + "')"

    sql := "SELECT * FROM servers where servername in " + result
    fmt.Println("sql: ", sql)

    db, err := sql.Open("mysql", dbname)
    if err != nil {
        log.Printf("Error %s when opening DB\n", err)
        return
    }
    defer db.Close()
    log.Printf("Connected to DB\n")
}

谢谢 SR

有阴影变量

sql := "SELECT * FROM servers where servername in " + result
    fmt.Println("sql: ", sql)

db, err := sql.Open("mysql", dbname)

您需要更改查询的变量名称sql