Golang – 从MySQL检索多个结果,然后将它们显示为JSON。

huangapple go评论85阅读模式
英文:

Golang - retrieve multiple results from MySQL, then display them as JSON

问题

最近,我正在学习Go(Golang)。我正在尝试使用Martini和jwt-go创建一个简单的Web服务。在检索单行数据并将其放入JSON作为响应方面,我没有遇到任何困难。但是,当处理多行数据时,情况就完全不同了。基本上,我参考了这里的被接受的答案

以下是我的代码片段:

m.Get("/users", func(params martini.Params, r render.Render) {
	db, err := sql.Open("mysql", "root:@/sirat_v2")
	if err != nil {
		panic(err.Error())
	}
	defer db.Close()

	rows, err := db.Query("SELECT user_id, nama FROM `users` WHERE password = ?", "asdfasdf")
	defer rows.Close()

	cols, err := rows.Columns()
	if err != nil {
		panic(err.Error())
	}

	partages := make([]*Partage, 0, 10)
	var user_id int
	var nama string
	for rows.Next() {
		err = rows.Scan(&user_id, &nama)
		if err != nil { /* error handling */
		}
		partages = append(partages, &Partage{user_id, nama})
	}
})

在尝试构建时,出现了一个错误,说Partage未定义。

英文:

Recently, I'm learning about Go (Golang). I'm trying to make a simple web service using Martini and jwt-go. I didn't find any difficulty in retrieving a single row data and put in JSON as the response. But, when dealing with multiple-rows, it's a whole different story. Basically, I refer to the accepted answer here.

Here is the piece of my code:

m.Get("/users", func(params martini.Params, r render.Render) {
	db, err := sql.Open("mysql", "root:@/sirat_v2")
	if err != nil {
		panic(err.Error())
	}
	defer db.Close()

	rows, err := db.Query("SELECT user_id, nama FROM `users` WHERE password = ?", "asdfasdf")
	defer rows.Close()

	cols, err := rows.Columns()
	if err != nil {
		panic(err.Error())
	}

	partages := make([]*Partage, 0, 10)
	var user_id int
	var nama string
	for rows.Next() {
		err = rows.Scan(&user_id, &nama)
		if err != nil { /* error handling */
		}
		partages = append(partages, &Partage{user_id, nama})
	}
})

When trying to build, there's an error said that Partage is undefined.

答案1

得分: 2

错误出现是因为您使用结构体Partage创建了一个对象,但您没有声明它。

type Partage struct {
    user_id string
    nama string
}

> 但是我如何将结果显示为JSON响应?我尝试了r.JSON(200, partages),但结果没有显示出来。

martini中,您可以使用r.JSON()rows打印为JSON。

m.Get("/users", func(params martini.Params, r render.Render) {
    // ... 

    r.JSON(200, map[string]interface{}{
        "data": rows
    })
})
英文:

The error showing up because you use struct Partage to create an object, but you haven't declared it.

type Partage struct {
    user_id string
    nama string
}

> But how do I display the result as JSON response? I've tried r.JSON(200, partages) but the results aren't displayed

In martini you can use r.JSON() to print rows as JSON

m.Get("/users", func(params martini.Params, r render.Render) {
    // ... 

    r.JSON(200, map[string]interface{}{
        data: rows
    })
})

huangapple
  • 本文由 发表于 2015年10月12日 11:31:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/33072861.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定