golang之连接mysql

  • go get github.com/go-sql-driver/mysql

  • 查询demo

db, err := sql.Open("mysql", config.GetMysqlLink("test",store_type))
if err!= nil{
		panic(err)
	}
	defer db.Close()
	sql:="select b2c_store_id from "+table+"  where store_id='"+storeid+"'"
	row:= db.QueryRow(sql)

	var b2c_store_id string
	row.Scan(&b2c_store_id)
	if b2c_store_id == "" {
		panic(errors.New("根据"+storeid+"未查询到统一车商id>b2c_store_id:"+b2c_store_id+"   sql:"+sql))
	}
	return b2c_store_id

执行insert等操作使用db.exec

  • 报错Golang, mysql: Error 1040: Too many connections

解决方案

This is what rows.Close() does. Your db.QueryRow("...") does the same thing internally when you call Scan(...).