Execute sql-prepared statement using slice

I wrote a function (In Go, of course) that inserts map[string]interface{}into mysql through this library.

Code explanation below:

  • Functions get stringcalled tables and map[string]interface{}called data.
  • I separate keys datainto keys (variables called columns) and values ​​(variables called values).
  • I am generating column_text from a column variable that will look like this: first_name, last_name, birth_day, date_added
  • I am generating from a variable a value called variable_text, which will look like this: ?, ?, ?, ?
  • I open a mysql connection: db, err := sql.Open("mysql", "user:pass@/database")
  • I create a prepared statement: 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 . ()? ( , , !)

:

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

EDIT: , .

!

+4
1

, Stmt.Exec args ...interface{}, 2 :

......
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...) 
+6

Source: https://habr.com/ru/post/1545575/


All Articles