A Scala JDBC connection and SQL SELECT example

Scala JDBC FAQ: How can I use the Java JDBC API in my Scala application?

If you want to use a SQL database with your Scala applications, it's good to know you can still use the traditional Java JDBC programming library to access databases. I just ran a simple JDBC connection and SQL SELECT test, and everything seems to work just as it does in Java.

A Scala, JDBC, and MySQL example

Without any further introduction, here's the source code for a complete Scala class (an object, actually) that connects to a MySQL database using nothing but plain old JDBC. In this example I'm connecting to a MySQL database server on my local computer, and then running a SQL SELECT query against the user table of the mysql database:

package jdbc

import java.sql.DriverManager
import java.sql.Connection

/**
 * A Scala JDBC connection example by Alvin Alexander,
 * https://alvinalexander.com
 */
object ScalaJdbcConnectSelect {

  def main(args: Array[String]) {
    // connect to the database named "mysql" on the localhost
    val driver = "com.mysql.jdbc.Driver"
    val url = "jdbc:mysql://localhost/mysql"
    val username = "root"
    val password = "root"

    // there's probably a better way to do this
    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 host, user FROM user")
      while ( resultSet.next() ) {
        val host = resultSet.getString("host")
        val user = resultSet.getString("user")
        println("host, user = " + host + ", " + user)
      }
    } catch {
      case e => e.printStackTrace
    }
    connection.close()
  }

}

As you can see, this Scala JDBC database connection example looks just like Java JDBC, which you can verify from my very old JDBC connection example and JDBC SQL SELECT example.

If you're new to JDBC and the MySQL URL shown above looks weird because I'm accessing the "mysql" database in the MySQL database server, remember that the general MySQL connection URL looks like this:

val url = "jdbc:mysql://hostname/database_name"

and if I was instead connecting to a database named drupal7, the MySQL URL would look like this instead:

val url = "jdbc:mysql://localhost/drupal7"

Scala, MySQL, and JDBC

If you were looking for a simple Scala JDBC connection example, I hope this short article was helpful. As you've seen, you can connect to MySQL or any other database (Postgresql, SQL Server, Oracle, etc.) using the usual Java JDBC technology from your Scala applications.