【问题标题】:Play Anorm and SQL connection播放 Anorm 和 SQL 连接
【发布时间】:2012-12-14 16:51:33
【问题描述】:

Play 2.0 in Scala with anorm 框架提供了两种与数据库交互的方法:

def withConnection[A](name: String)(block: Connection => A): A = {
    val connection = new AutoCleanConnection(getConnection(name))
    try {
      block(connection)
    } finally {
      connection.close()
    }
  }

  /**
   * Execute a block of code, in the scope of a JDBC transaction.
   * The connection and all created statements are automatically released.
   * The transaction is automatically committed, unless an exception occurs.
   *
   * @param name The datasource name.
   * @param block Code block to execute.
   */
  def withTransaction[A](name: String)(block: Connection => A): A = {
    withConnection(name) { connection =>
      try {
        connection.setAutoCommit(false)
        val r = block(connection)
        connection.commit()
        r
      } catch {
        case e => connection.rollback(); throw e
      }
    }
  }

现在我很清楚 withConnection 每次调用时都会获取并关闭连接。

为什么这两种方法每次都创建和关闭连接?这不是一个昂贵的过程吗?

【问题讨论】:

    标签: sql playframework-2.0 anorm


    【解决方案1】:

    em...没有问题,因为我们可以从连接池中检索连接。 所以 close() 方法只是将连接返回到池中,并没有真正关闭。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-30
      • 1970-01-01
      • 2016-02-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多