Scala, MySQL, JDBC, database test code (for Google Cloud Run and Cloud SQL)

I was having a problem connecting from a Google Cloud Run service to a Cloud SQL instance, so as part of the process of troubleshooting the problem I created the following Scala + MySQL + JDBC database test code. The idea was to create the code as simply as possible — with as few dependencies as possible — to try to understand the problem.

All this code requires is adding the MySQL connector to a usual build.sbt file:

libraryDependencies += "mysql" % "mysql-connector-java" % "8.0.27"

After that, my Scala/JDBC code just connects to a known database and performs a simple SQL query:

import java.sql.{Connection, DriverManager}
import java.io._

object DbTest extends App {

    val db       = "test_database"
    val username = "root"
    val password = "root"
    val url = s"jdbc:mysql://localhost:8889/${db}?useSSL=false"
    // val url = s"jdbc:mysql://10.0.0.1:3306/${db}?enabledTLSProtocols=TLSv1.2"
    // val url = s"jdbc:mysql://10.0.0.1:3306/${db}?enabledTLSProtocols=TLSv1,TLSv1.1,TLSv1.2"

    val driver = "com.mysql.jdbc.Driver"

    var connection: Connection = _
    try {
        println("ABOUT TO CONNECT AND RUN THE QUERY")
        Class.forName(driver)
        connection = DriverManager.getConnection(url, username, password)
        val statement = connection.createStatement
        val rs = statement.executeQuery("SELECT name FROM users")
        while (rs.next) {
            val name = rs.getString("name")
            println("NAME = %s".format(name))
        }
    } catch {
        case e: Exception =>
            println("GOT AN EXCEPTION!!!")
            val sw = new StringWriter()
            e.printStackTrace(new PrintWriter(sw))
            println(sw.toString)
    }
    connection.close
    println("AFTER connection.close (THE END)")

}

I show a few different MySQL URLs in the code because that was part of my experimenting process. I haven’t written any plain JDBC code like this in many years, but it ended up helping me solve the Cloud Run to Cloud SQL connection issue, so I thought I’d share the code here today. (The issue had to do with how Cloud Run connects to Cloud SQL, and by simplifying the code from a Play Framework application to just this code, I was able to properly understand the problem was with the MySQL driver/connector, which wasn’t even throwing an exception, it was just silently failing, which I could see (or not see) with this code.)

Reporting from Boulder, Colorado,
Alvin Alexander, Valley Programming