(GoLANG)* sql.DB将行扫描到字符串数组指针中 [英] (GoLANG) *sql.DB Scan rows into string array pointer

查看:73
本文介绍了(GoLANG)* sql.DB将行扫描到字符串数组指针中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始通过GO处理sql数据库.我有一个实例,其中将数据库连接中的行扫描到实例化切片中的嵌套结构的切片中.但是似乎无法正确执行它.是否有一些循环技术或引用在Golang中会有用.我提供了示例代码,可以提供其他任何内容.建立了连接池,只有在我去扫描行时,程序才会出现在连接池中.所以我的问题是,如果我想将多行(4行&2列)插入(老虎&狮子)对象(列)中,我该如何遍历并使用 rows.Scan ?

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
}

推荐答案

也许您正在寻找这样的东西:

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

这篇关于(GoLANG)* sql.DB将行扫描到字符串数组指针中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆