加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang database 全局

发布时间:2020-12-16 19:18:46 所属栏目:大数据 来源:网络整理
导读:重要的前提条件: 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 c


重要的前提条件:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读