6

I'm trying to do a golang db query like:

package main
import "fmt"
import "database/sql"
import _ "github.com/go-sql-driver/mysql"

var (
    name string
    id int
    age int
)

func main() {
    rows, err := sql.Open("mysql", "dbaccess:dbaccess@/dbaccess")
    if err != nil {
        panic(err.Error())
    }
    defer rows.Close()

    rows, err = sql.Query("select * from people where id = ?", 1)
    if err != nil {
        panic(err.Error())
    }
    defer rows.Close()

    for rows.Next() {
        err := rows.Scan(&id, &name)
        if err != nil {
        panic(err.Error())
        }
        fmt.Println(id, name)
    }
    err = rows.Err()
    if err != nil {
        panic(err.Error())
}

}

But I get the error:

20: undefined: sql.Query

I tried to put a colon before = but then got an error:

20: no new variables on left side of :=

what am I missing? I know there are other errors in the code, but just trying to debug/learn as I go.

0

1 Answer 1

5

Look at the documentation. Open returns a "pointer to a database", Query is a method that uses this pointer (and not sql). So you need to do something like this:

db, err := sql.Open("mysql", "dbaccess:dbaccess@/dbaccess")
if err != nil {
    panic(err.Error())
}
defer rows.Close()

rows, err := db.Query("select * from people where id = ?", 1)
if err != nil {
    panic(err.Error())
}
defer rows.Close()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.