duanliu6083 2019-09-23 13:55
浏览 123
已采纳

是否可以为多个请求准备一次SQL语句?

I have some SQL queries that do not change on every request (only it's parameter). So, instead of doing this for each request:

func HandleRequest() {
    rows, err := db.Query(sqlQuery, params...)
    // do something with data
}

Is it okay if for each reqest I do this instead:

// together with server initialization
stmt, err := db.Prepare(sqlQuery)

func HandleRequest() {
    rows, err := stmt.Query(params...)
    // do something with data
}
  • 写回答

1条回答 默认 最新

  • 普通网友 2019-09-23 14:23
    关注

    As the documentation of DB.Prepare() states:

    Multiple queries or executions may be run concurrently from the returned statement.

    It is safe for concurrent use, although the intended use for prepared statements is not to share them between multiple requests. The main reason is that a prepared statement (may) allocate resources in the DB server itself, and it's not freed until you call the Close() method of the returned statement. So I'd advise against it.

    The typical use case is if you have to run the same statement multiple times with different parameters, such as the example in the documentation:

    projects := []struct {
        mascot  string
        release int
    }{
        {"tux", 1991},
        {"duke", 1996},
        {"gopher", 2009},
        {"moby dock", 2013},
    }
    
    stmt, err := db.Prepare("INSERT INTO projects(id, mascot, release, category) VALUES( ?, ?, ?, ? )")
    if err != nil {
        log.Fatal(err)
    }
    defer stmt.Close() // Prepared statements take up server resources and should be closed after use.
    
    for id, project := range projects {
        if _, err := stmt.Exec(id+1, project.mascot, project.release, "open source"); err != nil {
            log.Fatal(err)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?