Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- type DB struct {
- *sql.DB
- }
- var db *DB
- func init() {
- dbinfo := fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable",
- DB_USER, DB_PASSWORD, DB_NAME)
- db, err := NewDB(dbinfo)
- checkErr(err)
- rows, err := db.Query("SELECT * FROM profile")
- checkErr(err)
- fmt.Println(rows)
- }
- func NewDB(dataSourceName string) (*DB, error) {
- db, err := sql.Open("postgres", dataSourceName)
- if err != nil {
- return nil, err
- }
- if err = db.Ping(); err != nil {
- return nil, err
- }
- return &DB{db}, nil
- }
- func (p *Profile) InsertProfile() {
- if db != nil {
- _, err := db.Exec(...)
- checkErr(err)
- } else {
- fmt.Println("DB object is NULL")
- }
- }
- db, err := NewDB(dbinfo)
- var err error
- db, err = NewDB(dbinfo)
- if err != nil {
- log.Fatal(err)
- }
- var db *sql.DB
- func init() {
- var err error
- db, err = sql.Open("yourdrivername", "somesource")
- if err != nil {
- log.Fatal(err)
- }
- if err = db.Ping(); err != nil {
- log.Fatal(err)
- }
- }
- package main
- import "fmt"
- var foo string = "global"
- func main() {
- fmt.Println(foo) // prints "global"
- // using := creates a new function scope variable
- // named foo that shadows the package scope foo
- foo := "function scope"
- fmt.Println(foo) // prints "function scope"
- printGlobalFoo() // prints "global"
- if true {
- foo := "nested scope"
- fmt.Println(foo) // prints "nested scope"
- printGlobalFoo() // prints "global"
- }
- // the foo created inside the if goes out of scope when
- // the code block is exited
- fmt.Println(foo) // prints "function scope"
- printGlobalFoo() // prints "global"
- if true {
- foo = "nested scope" // note just = not :=
- }
- fmt.Println(foo) // prints "nested scope"
- printGlobalFoo() // prints "global"
- setGlobalFoo()
- printGlobalFoo() // prints "new value"
- }
- func printGlobalFoo() {
- fmt.Println(foo)
- }
- func setGlobalFoo() {
- foo = "new value" // note just = not :=
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement