官方对mysql使用标准三步走:
sql="insert into users(age) values(?)";
正常的操作是
stmt = db.Prepare(sql)
stmt.Exec(...)
stmt.Close
prepare的时候会先从连接池里取一个连接,然后根据sql语句 创建一个stmt。但是对于同一种数据频繁数据的场景来说,一次prepare就可以了,没必要每次都重写创建一次stmt。
因此在mysqlConn的时候维护一个cache,以sql语句为key,对应的stmt为value。
同一个sql语句直接返回stmt。
当DB.Close的时候,会调用每次mysqlConn的Close,此时遍历cache释放stmt(stmt.Close()) ,释放cache。
具体操作看我github提交的源码。
更多评论
文档先确认下啊……
https://golang.org/pkg/database/sql/#Stmt
Stmt is a prepared statement. A Stmt is safe for concurrent use by multiple goroutines.
If a Stmt is prepared on a Tx or Conn, it will be bound to a single underlying connection forever. If the Tx or Conn closes, the Stmt will become unusable and all operations will return an error. If a Stmt is prepared on a DB, it will remain usable for the lifetime of the DB. When the Stmt needs to execute on a new underlying connection, it will prepare itself on the new connection automatically.
#3