database/sql 测试stmt

2019-12-30 17:25:21 浏览数 (1)

代码语言:javascript复制
func execAndPrepare()  {
    // create a connection (e.g. "postgres", "mysql", or "sqlite3")
    usr := "root"
    pwd := "shen6508"
    address := "localhost"
    dbName := "test"
    dbLink := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local",
        usr, pwd, address, dbName)

    if Db, err := sql.Open("mysql", dbLink); err != nil {
        print(err.Error())
    } else {
        Db.SetMaxOpenConns(300)

        // Prepare stmt and exec 1000 times.
        var err error
        var stmt *sql.Stmt
        SQL := "select * from tn where id = 70"
        stmt, err = Db.Prepare(SQL)
        if err != nil {
            log.Println(err.Error())
            return
        }
        defer stmt.Close()

        timeCount := 120
        // stmt exec 1000 times.
        stmtSt := time.Now() // get current time
        for i := 0; i < timeCount; i   {
            _, err = stmt.Query()
            if err != nil {
                log.Printf("stmt %d %v", i, err.Error())
                return
            }
        }
        log.Printf("%vn", time.Since(stmtSt))

        dbExecSt := time.Now()
        // Exec 1000 times.
        for i := 0; i < timeCount; i   {
            _, err = Db.Exec(SQL)
            if err != nil {
                log.Printf("dbExec %d %v", i, err.Error())
                return
            }
        }
        log.Printf("%vn", time.Since(dbExecSt))


    }

}

输出

代码语言:javascript复制
2019/12/24 15:55:30 174.5317ms
2019/12/24 15:55:30 15.9565ms

timeCount为150时会报错Too Many Connections

0 人点赞