golang database 全局

前端之家收集整理的这篇文章主要介绍了golang database 全局前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


重要的前提条件:

typeDB

type DB struct {
        // contains filtered or unexported fields
}

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.

funcOpen

func Open(driverName,dataSourceName string) (*DB,error)

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. Seehttps://golang.org/s/sqldriversfor 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.



##################

Go-MysqL-Driver的作者的回复http://stackoverflow.com/questions/17376207/how-to-share-MysqL-connection-between-http-goroutines


The database/sql package manages the connection pooling automatically for you.

sql.Open(..)returns a handle whichrepresents a connection pool,not a single connection. The database/sql package automatically opens a new connection if all connections in the pool are busy.

Applied to your code this means,that you just need to share the db-handle and use it in the HTTP handlers:

package main import ( "database/sql""fmt""github.com/gorilla/mux" _ "github.com/go-sql-driver/MysqL""log""net/http") var db *sql.DB // global variable to share it between main and the HTTP handler func main(){ fmt.Println("starting up" err error db, err = sqlOpen"MysqL""root@unix(/tmp/MysqL.sock)/mydb" // this does not really open a new connectionif!=nil logFatalf"Error on initializing database connection: %s" errError())} dbSetMaxIdleConns(100Ping// This DOES open a connection if necessary. This makes sure the database is accessible"Error on opening database connection: %s" r := muxNewRouter rHandleFunc"/" HomeHandler httpHandleListenAndServe":8080"nil func w httpResponseWriterhttpRequest msg stringQueryRow"SELECT msg FROM hello WHERE page=?""home").Scan(&msgFprintfw"Database Error!"else msg}

其余分析:http://studygolang.com/articles/3022
原文链接:https://www.f2er.com/go/190009.html

猜你在找的Go相关文章