Golang,MySQL,无法将查询数据追加到结构体列表中。

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

Golang, MySQL, Can't append query data into struct list

问题

当我尝试将数据解析为结构体并将其附加到切片中时,什么都没有得到。但是,如果我在MySQL Workbench中使用查询,我可以得到一些值...

query, err := db.Query("SELECT 'description','is_done' FROM tasks WHERE 'user_id' = ?;", userId)
if err != nil {
    return nil, err
}
defer query.Close()
var tasks []TodoUserDTO
var currentTask TodoUserDTO
for query.Next() {
    err = query.Scan(&currentTask.Description, &currentTask.IsDone)
    if err != nil {
        panic(err)
    }
    tasks = append(tasks, currentTask)
}

TodoDTO结构体如下所示:

type TodoUserDTO struct {
    Description string `json:"desc"`
    IsDone      bool   `json:"done"`
}
英文:

When I'm trying to parse data into struct and then append it into a slice, get nothing. But if I use query in MySQL workbench, I get some values....

query, err := db.Query("SELECT 'description','is_done' FROM tasks WHERE 'user_id' = ?;", userId)
if err != nil {
	return nil, err
}
defer query.Close()
var tasks []TodoUserDTO
var currentTask TodoUserDTO
for query.Next() {
	err = query.Scan(&currentTask.Description, &currentTask.IsDone)
	if err != nil {
		panic(err)
	}
	tasks = append(tasks, currentTask)
}

TodoDTO struct looks like this:

type TodoUserDTO struct {
    Description string `json:"desc"`
    IsDone      bool   `json:"done"`
}

答案1

得分: 2

根据代码来看,你在查询的SELECT语句中使用了错误的列名。SELECT语句应该包括tasks表中实际的列名,而不是列名的字面字符串。

尝试将SELECT语句更改为以下内容:

"SELECT description, is_done FROM tasks WHERE user_id = ?"

英文:

Based on the code, it looks like you're using the wrong column names in the SELECT statement of your query. The SELECT statement should include the actual column names of the columns in the tasks table, rather than the literal strings of the column names.

Try changing the SELECT statement to this:

"SELECT description, is_done FROM tasks WHERE user_id = ?"

huangapple
  • 本文由 发表于 2023年2月11日 00:07:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75413489.html
匿名

发表评论

匿名网友

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

确定