从数据库/ SQL查询获取结果

I have this:

tx, _ := db.Begin()
p := person.Person{Handle: "foo"}

rows, err := tx.Exec("INSERT INTO person (handle, email) VALUES ($1, $2) RETURNING id", p.Handle, p.Email).         

notice how it says RETURNING id in the sql query..how can I get the id from the first row return by the query?

I tried this:

var id string
defer rows.Close()
for rows.Next() {
    err := rows.Scan(&id, &name)
    if err != nil {
        log.Fatal(err)
    }
    log.Println(id, name)
}

but I get this compile error:

rows.Close undefined (type sql.Result has no field or method Close)

duanliang2017
duanliang2017 认为它应该是db.Close()而不是rows.Close()。
大约 2 年之前 回复

1个回答



Exec()</ code>获取的行上没有 Next()</ code> 。 但是它具有 LastInsertId()</ code>方法,您可以获取ID。</ p>
</ div>

展开原文

原文

There is no Next() on rows which get from Exec(). But it has LastInsertId() method which you can get the id.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问