How to use MySQL JDBC driver in an SBT Scala project?

In the SBT project class there should be a line:

 // Declare MySQL connector Dependency
  val mysql = "mysql" % "mysql-connector-java" % "5.1.12"

This will import the JDBC driver JAR file for MySQL.

Did you load the driver? If you use this Util class to fetch the connections, the driver will be loaded exactly one time:

// Util Class
object DaoUtil {
  import java.sql.{DriverManager, Connection}

  private var driverLoaded = false

  private def loadDriver()  {
    try{
      Class.forName("com.mysql.jdbc.Driver").newInstance
      driverLoaded = true
    }catch{
      case e: Exception  => {
        println("ERROR: Driver not available: " + e.getMessage)
        throw e
      }
    }
  }

  def getConnection(dbc: DbConnection): Connection =  {
    // Only load driver first time
    this.synchronized {
      if(! driverLoaded) loadDriver()
    }

    // Get the connection
    try{
      DriverManager.getConnection(dbc.getConnectionString)
    }catch{
      case e: Exception  => {
        println("ERROR: No connection: " + e.getMessage)
        throw e
      }
    }
  }
}

The code is taken from a simple SBT – MySQL tutorial I wrote some time ago. If you want to download the complete tutorial, see http://github.com/ollekullberg/SimpleOrder

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)