如何从切片中填充函数参数?

时间:2014-07-26 20:29:21

标签: sql go

我是golang的新手,请帮助一个菜鸟。

我正在尝试从数据片[]interface{}填充SQL插入语句。为了做到这一点,我需要调用带有参数的sql包的Exec函数,这些参数是我从输入通道获得的切片的各个部分。

最好显示有问题的代码:

// build INSERT vith variable number of columnes to fill
insertSql := "INSERT INTO " + database + "." + table + " VALUES ("
first := true
for _ = range format {
    if !first {
        insertSql += ","
    }
    first = false
    insertSql += "?"
}
insertSql += ")"

// prepare statment
stm, err := db.Prepare(insertSql)
if err != nil {
    return err
}

// execute the statement with data received via inputCh (type: []interface{})
outerLoop:
for {
    select {
        case data, opened := <-inputCh:
            if !opened {
                break outerLoop
            }

        // need to convert data of type []interface{} to individual arguments for Exec
        _, err := stm.Exec(XXXXXXX)
        if err != nil {
            return err
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您必须将...令牌附加到切片。有关详细信息,请参阅documentation about variadic parameters