Advertisement
Guest User

Untitled

a guest
Apr 1st, 2016
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "encoding/json"
  6. "github.com/jackc/pgx"
  7. "log"
  8. )
  9.  
  10. var schema = `
  11. CREATE TABLE person (
  12. first_name text,
  13. last_name text,
  14. contact JSON
  15. );`
  16.  
  17. type Person struct {
  18. FirstName string `db:"first_name"`
  19. LastName string `db:"last_name"`
  20. Contact map[string]string `db:"contact"`
  21. }
  22.  
  23. func main() {
  24. config := pgx.ConnConfig{
  25. Host: "localhost",
  26. User: "test",
  27. Password: "test",
  28. Database: "test",
  29. }
  30.  
  31. conn, err := pgx.Connect(config)
  32. if err != nil {
  33. log.Fatalln(err)
  34. }
  35. defer conn.Close()
  36.  
  37. // exec the schema or fail
  38. _, err = conn.Exec("DROP TABLE IF EXISTS person;")
  39. if err != nil {
  40. panic(err)
  41. }
  42.  
  43. _, err = conn.Exec(schema)
  44. if err != nil {
  45. panic(err)
  46. }
  47.  
  48.  
  49. var person Person
  50. contact := map[string]string{"email": "jmoiron@jmoiron.net"}
  51. contact_json, _ := json.Marshal(contact)
  52.  
  53. _, err = conn.Exec("INSERT INTO person (first_name, last_name, contact) VALUES ($1, $2, $3)", "Jason", "Moiron", contact_json)
  54. if err != nil {
  55. panic(err)
  56. }
  57.  
  58. row := conn.QueryRow("SELECT first_name, last_name, contact FROM person LIMIT 1")
  59. err = row.Scan(&person.FirstName, &person.LastName, &person.Contact)
  60. if err != nil {
  61. panic(err)
  62. }
  63. fmt.Printf("%v", person)
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement