Skip to content

Instantly share code, notes, and snippets.

@ryansmith3136
Created January 4, 2013 03:41
Show Gist options
  • Select an option

  • Save ryansmith3136/4449712 to your computer and use it in GitHub Desktop.

Select an option

Save ryansmith3136/4449712 to your computer and use it in GitHub Desktop.
Simple postgres array parsing in Go.
package main
import (
"database/sql"
"fmt"
_ "github.com/bmizerany/pq"
"strconv"
"strings"
)
func main() {
// Assuming: create table data(vals numeric[]);
db, err := sql.Open("postgres", "user=ryandotsmith dbname=test sslmode=disable")
db.Exec("insert into data values('{32.0, 49}')")
rows, err := db.Query("SELECT vals from data")
if err != nil {
fmt.Printf("error=%s\n", err)
return
}
for rows.Next() {
var x []byte
rows.Scan(&x)
// pq returns something like: {1.0, 2.0}
// let us remove the { and the }
trimed := x[1 : len(x)-1]
// Assuming the numbers are seperated by commas.
numbers := strings.Split(string(trimed), ",")
// Showing that we can do cool things with floats.
var sum float64
for _, x := range numbers {
f, err := strconv.ParseFloat(x, 64)
if err == nil {
sum += f
}
}
fmt.Printf("sum=%f\n", sum)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment