Play、Scala、JDBC 和并发

Play, Scala, JDBC and concurrency

我有一个通过 JDBC 访问数据库的 Scala class:

class DataAccess {

  def select = {

    val driver = "com.mysql.jdbc.Driver"
    val url = "jdbc:mysql://localhost:3306/db"
    val username = "root"
    val password = "xxxx"

    var connection:Connection = null

    try {
      // make the connection
      Class.forName(driver)
      connection = DriverManager.getConnection(url, username, password)

      // create the statement, and run the select query
      val statement = connection.createStatement()
      val resultSet = statement.executeQuery("SELECT name, descrip FROM table1")
      while ( resultSet.next() ) {
        val name = resultSet.getString(1)
        val descrip = resultSet.getString(2)
        println("name, descrip = " + name + ", " + descrip)
      }
    } catch {
      case e => e.printStackTrace
    }
    connection.close()
  }

}

我在我的 Play 应用程序中访问这个 class,像这样:

  def testSql = Action { 
       val da = new DataAccess
       da.select()
       Ok("success")
  }

方法testSql 可能会被多个用户调用。问题是:while ( resultSet.next() ) 循环(或 class 的任何其他部分)是否存在竞争条件?

注意:我需要使用 JDBC,因为 SQL 语句是动态的。

不可以。

每个线程都在使用 ResultSet 的不同本地实例,因此无法同时访问同一对象。