I know that for string array []string
I can use strings.Join(a []string, ',')
but I want to do the same thing for an integer array []int
.
My usecase is something like this for a query where variants
is []map[string]int
var Ids []int
sqlStr := "select id from mapping where my_id in ("
for _, mp := range variants {
sqlStr += "?,"
Ids = append(Ids, mp["id"])
}
sqlStr = strings.TrimRight(sqlStr, ",")
rows, err := db.Query(sqlStr+")", strings.Join(Ids, ',')) // I can't do this because Join needs String array
How to achieve this?
Use string join() function to get the comma separated strings.
Below are the various methods to convert an Array to String in Java: Arrays. toString() method: Arrays. toString() method is used to return a string representation of the contents of the specified array.
The split() method is used to split a string on the basis of a separator. This separator could be defined as a comma to separate the string whenever a comma is encountered. This method returns an array of strings that are separated.
Make IDs
a []string
and convert the integers when you append them
var IDs []string
for _, i := range []int{1, 2, 3, 4} {
IDs = append(IDs, strconv.Itoa(i))
}
fmt.Println(strings.Join(IDs, ", "))
https://play.golang.org/p/xrfuMRjgiI
I would prefer to use json.Marshal
. It is much simple and easy to use.
data := []int{100, 200, 300}
s, _ := json.Marshal(data)
fmt.Println(strings.Trim(string(s), "[]"))
GoPlaygroundLink
I hope this helps you. Please feel free to ask in case of doubts. WebsiteLink
Here is an efficient way to do that:
func sqlIntSeq(ns []int) string {
if len(ns) == 0 {
return ""
}
// Appr. 3 chars per num plus the comma.
estimate := len(ns) * 4
b := make([]byte, 0, estimate)
// Or simply
// b := []byte{}
for _, n := range ns {
b = strconv.AppendInt(b, int64(n), 10)
b = append(b, ',')
}
b = b[:len(b)-1]
return string(b)
}
You can use it in the SQL queries like that:
query := `SELECT * FROM table WHERE id IN (` + sqlIntSeq(ids) + `)`
Playground: https://play.golang.org/p/zi7YYetGu7.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With