请教一个mysql事务问题
发布于 3 年前 作者 gxsandzxl 2395 次浏览 来自 问答

项目中每天会去请求数据库查询数据,用到了事务来创建临时表,第一次查询的时候没问题,第二次查询的时候报错表格已建立,以下是代码。

  async handler() {
    this.connection = await this.pMysql.getConnection()
    await this.connection.beginTransaction()
    try {
      const limit = pLimit(10) // p-limit库
      let promise = []
      promise.push(limit(() => this.doSomething1()))
      promise.push(limit(() => this.doSomething2()))
      promise.push(limit(() => this.doSomething3()))
      promise.push(limit(() => this.doSomething4()))
      // ...

      await Promise.all(promise)

      await this.connection.commit()
      await this.connection.release()
    } catch (e) {
      await this.connection.rollback()
      await this.connection.release()
      throw e
    }
  }

问题可以通过删除表来解决。但我想知道为什么第二次创建临时表会报错?临时表不是和connection的生命周期绑定的吗?

3 回复

应该用:

  try {
  } finally {
  }

问题是await this.connection.release()语句重复导致?

@xinggsf 应该不是,报错里没有写release出错了

@gxsandzxl this.connection = await this.pMysql.getConnection() 这行语句是从连接池中取数据库连接实例。release()仅仅是释放连接实例到连接池,并没有销毁。因此所属的连接会话仍然存在,与会话相关的资源仍然存在

回到顶部