Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return DB (database/sql) type in golang?

Tags:

postgresql

go

I use Go with PostgreSQL using github.com/lib/pq.

I want to call this opendb() function in other functions but I'm having problem with the return value.

 package database

    import (
            "fmt"
            "database/sql"
            _ "github.com/lib/pq"
    )

    const (
            host = "localhost"
            port = 5432
            user = "postgres"
            password = "pgpassword"
            dbname = "postgres"
    )

    func opendb() (*DB) {
            psqlInfo := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s " +
              "sslmode=disable", host, port, user, password, dbname)

            db, err := sql.Open("postgres", psqlInfo)

            if err != nil {
                    panic(err)
            }

            defer db.Close()

            return db
    }

If you run this:

$ go run main.go

It will show this error:

error:

    undefined: DB
like image 824
lab0 Avatar asked Jul 09 '18 17:07

lab0


People also ask

What is GOS DB?

Geographical Operations System, mapping and database software for telecommunications companies.

What is Tx SQL?

Tx, which represents a transaction. In addition to Commit and Rollback methods representing transaction-specific semantics, sql. Tx has all of the methods you use to perform common database operations.


1 Answers

the return datatype should be *sql.DB
changing
func opendb() (*DB) {

to

func opendb() (*sql.DB) {

should work

like image 101
Shiva Kishore Avatar answered Sep 29 '22 01:09

Shiva Kishore