英文:
How to fill function arguments from slice?
问题
我是你的中文翻译助手,以下是你要翻译的内容:
我是golang的新手,请帮助一个菜鸟。
我正在尝试从数据切片[]interface{}
中填充SQL插入语句。为了做到这一点,我需要使用从输入通道获取的切片的各个部分作为参数调用sql包的Exec函数。
最好通过以下代码片段展示问题:
// 构建具有可变列数的INSERT语句
insertSql := "INSERT INTO " + database + "." + table + " VALUES ("
first := true
for _ = range format {
if !first {
insertSql += ","
}
first = false
insertSql += "?"
}
insertSql += ")"
// 准备语句
stm, err := db.Prepare(insertSql)
if err != nil {
return err
}
// 使用通过inputCh接收到的数据(类型为[]interface{})执行语句
outerLoop:
for {
select {
case data, opened := <-inputCh:
if !opened {
break outerLoop
}
// 需要将类型为[]interface{}的数据转换为Exec的各个参数
_, err := stm.Exec(XXXXXXX)
if err != nil {
return err
}
}
}
请提供XXXXXXX部分的代码,以便我可以帮助你进行翻译。
英文:
I'm new to golang, pls help a noob.
I'm trying to fill a SQL insert statement from slice of data []interface{}
. In order to do that I need to call Exec function of sql package with arguments which are individual parts of slice I get from input channel.
Best to show piece of code in question:
<!-- language: lang-go -->
// 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
得分: 2
你需要将...
标记添加到你的切片中。有关可变参数的更多详细信息,请参阅关于可变参数的文档。
英文:
You have to append the ...
token to your slice. See the documentation about variadic parameters for more details.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论