0
votes

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
Do you want to scan rows of zoos or rows of structures? - mkopriva
@mkopriva rows of zoo's - Sam
Then on each iteration initialize a new zoo instance, scan the columns into its fields and at the end append the instance to a slice of zoos that was declared outside of the loop. - mkopriva
can you layout some form of example @mkopriva - Sam

1 Answers

0
votes

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)
}