Creating a global DB with database/sql?

760 views
Skip to first unread message

Ken GoNoob

unread,
Dec 12, 2013, 11:10:54 AM12/12/13
to golan...@googlegroups.com
I'm trying to create a global "DB" type variable after opening with sql.Open(). Conceptually something like:

var MyDB *DB   // this fails - DB is not a recognized type

func init() {
    MyDB, err = sql.Open(DBparms....)
}

func accessDB()
     rows, err := MyDB.Query(query...)  // use the db connection that was opened in init()
}

I've tried a variety of things to make a global "DB" or "*DB" variable, but I'm not getting how it's supposed to work. Does MyDB have to be passed as an argument to all of the functions requiring it?
If so, how do you declare the functions since it doesn't recognize DB as a valid type?
Ken

Peter Bourgon

unread,
Dec 12, 2013, 11:14:28 AM12/12/13
to Ken GoNoob, golang-nuts
On Thu, Dec 12, 2013 at 5:10 PM, Ken GoNoob <drke...@gmail.com> wrote:
> I'm trying to create a global "DB" type variable after opening with
> sql.Open(). Conceptually something like:
>
> var MyDB *DB // this fails - DB is not a recognized type

You probably mean *sql.DB, here.

>
> func init() {
> MyDB, err = sql.Open(DBparms....)
> }
>
> func accessDB()
> rows, err := MyDB.Query(query...) // use the db connection that was
> opened in init()
> }
>
> I've tried a variety of things to make a global "DB" or "*DB" variable, but
> I'm not getting how it's supposed to work. Does MyDB have to be passed as an
> argument to all of the functions requiring it?
> If so, how do you declare the functions since it doesn't recognize DB as a
> valid type?
> Ken
>
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts...@googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.

chris dollin

unread,
Dec 12, 2013, 11:16:46 AM12/12/13
to Ken GoNoob, golan...@googlegroups.com

Missing package name for type?

--

Kevin Gillette

unread,
Dec 12, 2013, 7:23:37 PM12/12/13
to golan...@googlegroups.com, Ken GoNoob, pe...@bourgon.org
Don't forget to also import "database/sql" in that file as well, otherwise the sql identifier will be meaningless.

Ken MacDonald

unread,
Dec 13, 2013, 2:54:33 PM12/13/13
to Kevin Gillette, golan...@googlegroups.com, pe...@bourgon.org
Kevin, Chris, Peter,
Thanks (duh). Taking some time to get used to Go syntax for things, but starting to light a spark :-)
Ken
Reply all
Reply to author
Forward
0 new messages