美文网首页
database/sql 测试stmt

database/sql 测试stmt

作者: 不存在的里皮 | 来源:发表于2019-12-24 15:56 被阅读0次
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("%v\n", 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("%v\n", time.Since(dbExecSt))


    }

}

输出

2019/12/24 15:55:30 174.5317ms
2019/12/24 15:55:30 15.9565ms

timeCount为150时会报错Too Many Connections

相关文章

网友评论

      本文标题:database/sql 测试stmt

      本文链接:https://www.haomeiwen.com/subject/lqoxoctx.html