I'm new to Golang and to compiled, statically-typed programming in general. All my prior experience has been with Python.
This paradigm shift has been both frustrating (programs rarely compile) and rewarding as I'm finally getting my head around many concepts that were previously foreign to me (garbage collection, pointers, scope).
Can someone explain to me on a conceptual level why this program won't compile and the syntax to fix it? I'm simply trying to query a DB and print the results:
package main
import (
"database/sql"
"log"
_ "github.com/denisenkom/go-mssqldb"
)
func main() {
db, err := sql.Open("sqlserver", "odbc:server=myServer;user id=myName;password=myPassword;")
if err != nil {
log.Fatal(err)
}
defer db.Close()
q()
}
func q() {
var (
id int
name string
)
rows, err := db.Query("SELECT id, name FROM myTable")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
err := rows.Scan(&id, &name)
if err != nil {
log.Fatal(err)
}
log.Println(id, name)
}
err = rows.Err()
if err != nil {
log.Fatal(err)
}
}
The error I'm getting is:
undefined: db in db.Query
The query works when I put the logic inside q() in the main function - I'm assuming this is because functions have "local" scope (is that the correct terminology?) and I need to define the db object as I have in the main function.
If this is the case - how do I run the q() function without repeating myself in establishing the db connection? Is this where "pointers" come in? Also, I'm still uncertain as to what the ampersands are doing here:
err := rows.Scan(&id, &name)
Thanks