(GoLANG) *sql.DB Scan rows into string array pointer

别来无恙 提交于 2021-01-29 12:09:16

问题


I'm fairly new to handling sql databases through GO. I have an instance where I am scanning rows from my DB connection, into an slices of a nested struct in an instantiated slice. But can't seem to properly preform it. Is there some looping techniques or references that would be of some use in Golang. I have provided example code and can provide anything else. The connection pool is established and only when I go to scan the rows is where my program craps out. So my question is, if there are multiple rows (4 rows & 2 columns) that I want to insert into the (tiger & lion) objects (columns) how would i loop over and do that with the rows.Scan??

rows, err := db.Query(`Query`)

if err != nil {
		//error
		return 
	} else {
		// logging
	}
}

for rows.Next() {
		ref := &structurre{}

		err := rows.Scan(&ref.number, &ref.animal[0].tiger, &ref.animal[o].lion)
		if err != nil {
			logEntry.Info(err)
			return details, err

		}
		details = append(details, ref)
}
  
type structure struct {
 number string
 animal []*zoo
}

type zoo struct {
  tiger string
  lion string
}

回答1:


Maybe you're looking for something like this:

    type zoo struct {
    tiger string
    lion  string
}

type structure struct {
    number string
    animal []*zoo
}

var ref []structure

rows, err := db.QueryContext(ctx, `query`, `args...`)

if err != nil {
    //error
    return err
}
// logging

for rows.Next() {
    var scans structure
    err = rows.Scan(&scans.number, &scans.animal[0].tiger, &scans.animal[0].lion)
    if err != nil {
        fmt.Println(err)
        if err == sql.ErrNoRows {
            fmt.Println("No Rows found")
        }
        return err

    }
    ref = append(ref, scans)
}


来源:https://stackoverflow.com/questions/60763064/golang-sql-db-scan-rows-into-string-array-pointer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!