在 Go 中,我试图将 一个 传递给 函数从 .我确信这是一个已解决的问题,但我无法弄清楚。interface{}statement.Exec()go-sqlite3
基本上,我有一个行数据,我想将其传递给一个函数,该函数将它插入到sqlite db中。问题是我希望能够以编程方式控制函数中的内容structstatement.Exec()
以下是摘录:
type hostRows struct {
domain string
}
type clientRows struct {
name string
}
func main() {
...
data := hostRows{domain: "dom.com"}
insertRow(sqliteDatabase, data)
data2 := clientRows{name: "bob"}
insertRow(sqliteDatabase, data2)
...
}
func insertRow(db *sql.DB, row interface{}) {
insertSQL := "INSERT INTO table(col) VALUES (?)"
statement, _ := db.Prepare(insertSQL)
statement.Exec(row) // here's the issue, how can I extract the element in the interface to pass it to the function for Exec to understand
}
我知道在此示例中,我可以将行类型硬编码为结构和类型,但现在代码将中断到传递客户端结构时。statement.Exec(row.(hostRows).domain)
这是函数的减速Exec
func (s *Stmt) Exec(args ...interface{}) (Result, error)
我尝试过玩,但到目前为止它还没有对我有用。我目前唯一的解决方案是使用一个条件,可以检查并准备正确的命令,但这还不够狡猾。reflectswitchExec
type hostRows struct {
domain string
}
type clientRows struct {
name string
}
func main() {
...
data := hostRows{domain: "dom.com"}
insertRow(sqliteDatabase, 1, data)
data2 := clientRows{name: "bob"}
insertRow(sqliteDatabase, 2, data2)
...
}
func insertRow(db *sql.DB, i int, row interface{}) {
insertSQL := "INSERT INTO table(col) VALUES (?)"
statement, _ := db.Prepare(insertSQL)
// This basically could be a working solution, but I'm sure there is a better one
switch i {
case 1:
data := row.(hostRows)
statement.Exec(data.domain)
case 2:
data := row.(clientRows)
statement.Exec(data.name)
}
}
编辑:更正了 INSERT 语句 ;忘记列。更正为 edit2:添加了第二个示例statement.Exec(row.domain)statement.Exec(row.(hostRows).domain)
哈士奇WWW
相关分类