Skip to content

Instantly share code, notes, and snippets.

@fho
Created May 27, 2019 13:16
Show Gist options
  • Save fho/777ccc77971612f3659cbdf5cef27ede to your computer and use it in GitHub Desktop.
Save fho/777ccc77971612f3659cbdf5cef27ede to your computer and use it in GitHub Desktop.
dbquery test
package main
import (
"bufio"
"database/sql"
"fmt"
"os"
_ "github.com/lib/pq" // postgres driver
)
func checkErr(err error) {
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
type op int
const (
query op = iota
ping
)
func readKeyboardInput() op {
reader := bufio.NewReader(os.Stdin)
for {
fmt.Println("Press 'q' to do an SQL query")
fmt.Println("Press 'p' to do a db ping")
fmt.Println("Press 'e' to exit")
input, _, err := reader.ReadRune()
if err != nil {
fmt.Println(err)
continue
}
switch input {
case 'q':
return query
case 'p':
return ping
case 'e':
os.Exit(0)
}
}
}
func main() {
var opcnt int
if len(os.Args) != 2 {
fmt.Printf("usage: %s <psql-dsn>\n", os.Args[0])
os.Exit(1)
}
dsn := os.Args[1]
db, err := sql.Open("postgres", dsn)
checkErr(err)
for {
fmt.Printf("#%d\n", opcnt)
op := readKeyboardInput()
opcnt++
switch op {
case query:
_, err = db.Exec("SELECT 'HELLO'")
if err != nil {
fmt.Println("ERR:" + err.Error())
} else {
fmt.Println("SQL query successful")
}
case ping:
err := db.Ping()
if err != nil {
fmt.Println("ERR:" + err.Error())
} else {
fmt.Println("Ping successful")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment