Golang database/sql.DB type examples

package database/sql

DB is a database handle representing a pool of zero or more underlying connections. It's safe for concurrent use by multiple goroutines.

The sql package creates and frees connections automatically; it also maintains a free pool of idle connections. If the database has a concept of per-connection state, such state can only be reliably observed within a transaction. Once DB.Begin is called, the returned Tx is bound to a single connection. Once Commit or Rollback is called on the transaction, that transaction's connection is returned to DB's idle connection pool. The pool size can be controlled with SetMaxIdleConns.

Golang database/sql.DB type usage examples

Example 1:

 func getServerVersion(t *testing.T, db *sql.DB) int {
 var version int
 err := db.QueryRow("SHOW server_version_num").Scan(&version)
 if err != nil {
 t.Fatal(err)
 }
 return version
 }

Example 2:

 // mysql session store
 type MysqlSessionStore struct {
 c *sql.DB
 sid string
 lock sync.RWMutex
 values map[interface{}]interface{}
 }

Reference :

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

Advertisement