Created
June 6, 2018 07:29
-
-
Save usk81/4ab6e19f3f11a4c485e92f2c045ecd5c to your computer and use it in GitHub Desktop.
bulk insert on duplicate key のクエリを作る https://play.golang.org/p/40qF3edyN1C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"strings" | |
) | |
type Value struct { | |
ValA string | |
ValB string | |
ValC string | |
} | |
const table = "table" | |
func main() { | |
rs := []Value{ | |
Value{ | |
ValA: "foo", | |
ValB: "bar", | |
ValC: "fizz", | |
}, | |
Value{ | |
ValA: "foo", | |
ValB: "bar", | |
ValC: "fizz", | |
}, | |
Value{ | |
ValA: "foo", | |
ValB: "bar", | |
ValC: "fizz", | |
}, | |
Value{ | |
ValA: "foo", | |
ValB: "bar", | |
ValC: "fizz", | |
}, | |
Value{ | |
ValA: "foo", | |
ValB: "bar", | |
ValC: "fizz", | |
}, | |
} | |
if len(rs) == 0 { | |
return | |
} | |
ss := make([]string, len(rs) * 3) | |
base := "INSERT INTO %s (id, valb, valc) VALUES %s ON DUPLICATE KEY UPDATE valb = VALUES(valb), valc = VALUES(valc)" | |
q := fmt.Sprintf(base, table, strings.TrimRight(strings.Repeat("(?, ?, ?),", len(rs)), ",")) | |
for i, r := range rs { | |
ss[(i*3)] = r.ValA | |
ss[(i*3)+1] = r.ValB | |
ss[(i*3)+2] = r.ValC | |
} | |
fmt.Printf("query: %s\n", q) | |
fmt.Printf("value: %#v\n", ss) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment