duancifu6769 2017-02-16 22:22
浏览 45
已采纳

Golang,指针,函数

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

  • 写回答

2条回答 默认 最新

  • drr25281 2017-02-16 22:33
    关注

    db var is defined at main func scope, so your q func don't "see" it. You have to pass as pointer to q method. Something like that:

    func q(db *sql.DB) {
       ...
    }
    

    Your db var in main is already a pointer to sql.DB struct, so you just have to do q(db) call in main func and it'll work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。