英文:
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(¤tTask.Description, ¤tTask.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 = ?"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论