0

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
}

4
  • Do you want to scan rows of zoos or rows of structures? Commented Mar 19, 2020 at 18:39
  • @mkopriva rows of zoo's Commented Mar 19, 2020 at 18:43
  • 1
    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. Commented Mar 19, 2020 at 18:52
  • can you layout some form of example @mkopriva Commented Mar 19, 2020 at 18:56

1 Answer 1

0

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)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.