问题
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