Golang database/sql.Open() function examples

package database/sql

Open opens a database specified by its database driver name and a driver-specific data source name, usually consisting of at least a database name and connection information.

Most users will open a database via a driver-specific connection helper function that returns a *DB. No database drivers are included in the Go standard library. See http://golang.org/s/sqldrivers for a list of third-party drivers.

Open may just validate its arguments without creating a connection to the database. To verify that the data source name is valid, call Ping.

The returned DB is safe for concurrent use by multiple goroutines and maintains its own pool of idle connections. Thus, the Open function should be called just once. It is rarely necessary to close a DB.

Golang database/sql.Open() function usage examples

Example 1:

 p := path.Join(os.TempDir(), "sqlite.db")
 conn, err := sql.Open("sqlite3", p)

Example 2:

 var (
 dbType = flag.String("dbType", "sqlite3", "db type")
 dbUrl  = flag.String("dbUrl", "sdata.db", "db url")
 )
 db, _ := sql.Open(*dbType, *dbUrl)
 defer db.Close()
 result, err := db.Exec("insert into t_sdata (data,tp) values(?,?)", data, _type)
 ...

References :

https://github.com/wendal/shortit/blob/master/golang/shortit.go

http://golang.org/pkg/database/sql/#Open

Advertisement