Advertisement
Guest User

Untitled

a guest
Apr 24th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. type DB struct {
  2. *sql.DB
  3. }
  4.  
  5. var db *DB
  6.  
  7. func init() {
  8. dbinfo := fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable",
  9. DB_USER, DB_PASSWORD, DB_NAME)
  10.  
  11. db, err := NewDB(dbinfo)
  12. checkErr(err)
  13.  
  14. rows, err := db.Query("SELECT * FROM profile")
  15. checkErr(err)
  16.  
  17. fmt.Println(rows)
  18. }
  19.  
  20. func NewDB(dataSourceName string) (*DB, error) {
  21. db, err := sql.Open("postgres", dataSourceName)
  22. if err != nil {
  23. return nil, err
  24. }
  25. if err = db.Ping(); err != nil {
  26. return nil, err
  27. }
  28. return &DB{db}, nil
  29. }
  30.  
  31. func (p *Profile) InsertProfile() {
  32. if db != nil {
  33. _, err := db.Exec(...)
  34. checkErr(err)
  35. } else {
  36. fmt.Println("DB object is NULL")
  37. }
  38. }
  39.  
  40. db, err := NewDB(dbinfo)
  41.  
  42. var err error
  43. db, err = NewDB(dbinfo)
  44. if err != nil {
  45. log.Fatal(err)
  46. }
  47.  
  48. var db *sql.DB
  49.  
  50. func init() {
  51. var err error
  52. db, err = sql.Open("yourdrivername", "somesource")
  53. if err != nil {
  54. log.Fatal(err)
  55. }
  56. if err = db.Ping(); err != nil {
  57. log.Fatal(err)
  58. }
  59. }
  60.  
  61. package main
  62.  
  63. import "fmt"
  64.  
  65. var foo string = "global"
  66.  
  67. func main() {
  68. fmt.Println(foo) // prints "global"
  69.  
  70. // using := creates a new function scope variable
  71. // named foo that shadows the package scope foo
  72. foo := "function scope"
  73. fmt.Println(foo) // prints "function scope"
  74. printGlobalFoo() // prints "global"
  75.  
  76. if true {
  77. foo := "nested scope"
  78. fmt.Println(foo) // prints "nested scope"
  79. printGlobalFoo() // prints "global"
  80. }
  81. // the foo created inside the if goes out of scope when
  82. // the code block is exited
  83.  
  84. fmt.Println(foo) // prints "function scope"
  85. printGlobalFoo() // prints "global"
  86.  
  87. if true {
  88. foo = "nested scope" // note just = not :=
  89. }
  90.  
  91. fmt.Println(foo) // prints "nested scope"
  92. printGlobalFoo() // prints "global"
  93.  
  94. setGlobalFoo()
  95. printGlobalFoo() // prints "new value"
  96. }
  97.  
  98. func printGlobalFoo() {
  99. fmt.Println(foo)
  100. }
  101.  
  102. func setGlobalFoo() {
  103. foo = "new value" // note just = not :=
  104. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement