我写了一个函数(当然是Go),map[string]interface{}通过这个库插入mysql .
string被调用的表并map[string]interface{}调用数据.datato键(称为列的变量)和值(称为值的变量)分开.first_name, last_name, birth_day, date_added?, ?, ?, ?db, err := sql.Open("mysql", "user:pass@/database")stmt, err := db.Prepare("INSERT INTO " + table + " ( " + columns_text + " ) VALUES ( " + values_text + " )")stmt.Exec()命令无法接收像这样的切片(数组):stmt.Exec(values)只有像这样的值:stmt.Exec(values[0], values[1], values[2]...)我来自PHP,其中PDO :: Statement在执行时可以接收数组.如何用slice(Array)执行语句?(如果我可以用不同的库来做,请写出库的名称以及如何使用它,谢谢!)
func insertToDB(table string, data map[string]interface{}) {
columns := make([]interface{}, 0, len(data))
values := make([]interface{}, 0, len(data))
for key, _ := range data {
columns = append(columns, key)
values = append(values, data[key])
}
columns_text := ""
i := 0
of := len(data)
for i < of {
column := columns[i].(string)
if i == 0 {
columns_text = column
} else {
columns_text = columns_text + ", " + column
}
i++
}
fmt.Println(columns_text + " = " + table)
values_text := ""
i = 0
for i < of {
if i == 0 {
values_text = "?"
} else {
values_text = values_text + ", ?"
}
i++
}
fmt.Println(values_text)
fmt.Println(values)
fmt.Println(data)
db, err := sql.Open("mysql", "root:root@/bacafe")
if err != nil {
return -1, err
}
defer db.Close()
stmtIns, err := db.Prepare("INSERT INTO " + table + " ( " + columns_text + " ) VALUES ( " + values_text + " )")
if err != nil {
return -1, err
}
defer stmtIns.Close() // Close the statement when we leave main() / the program terminates
result, err := stmtIns.Exec(values...)
if err != nil {
return -1, err
} else {
insertedID, err := result.LastInsertId()
if err != nil {
return -1, err
} else {
return int(insertedID), nil
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:我编辑了上面的功能,它现在完美地运作.
谢谢!
你是在正确的轨道上.然而Stmt.Exec需要args ...interface{},所以你的具体的例子,你需要改变两件事情:
......
values := make([]interface{}, 0, len(data))
......
//adding ... expands the values, think of it like func.apply(this, array-of-values) in
// javascript, in a way.
_, err = stmtIns.Exec(values...)
Run Code Online (Sandbox Code Playgroud)