How to read from two databases at the same time with ScalikeJdbc

This example shows how to connect-to and read-from multiple databases with ScalikeJdbc (a Scala JDBC library). I assume you already know how to use ScalikeJdbc with one database, so I’m only going to show the code and configuration file. (I’m not going to explain the details.)

The ScalikeJdbc configuration file

My ScalikeJdbc code is in an SBT project, so the ScalikeJdbc configuration file is at src/main/resources/application.conf:

# KBHR database
db.kbhr.driver="com.mysql.jdbc.Driver"
db.kbhr.url="jdbc:mysql://localhost:8889/kbhr"
db.kbhr.user="root"
db.kbhr.password="root"
db.kbhr.poolInitialSize=5
db.kbhr.poolMaxSize=10
db.kbhr.poolConnectionTimeoutMillis=1000

# KBHR_GEO database
db.kbhr_geo.driver="com.mysql.jdbc.Driver"
db.kbhr_geo.url="jdbc:mysql://localhost:8889/kbhr_geo_location"
db.kbhr_geo.user="root"
db.kbhr_geo.password="root"
db.kbhr_geo.poolInitialSize=5
db.kbhr_geo.poolMaxSize=10
db.kbhr_geo.poolConnectionTimeoutMillis=1000

# Global settings (these are probably not all needed)
scalikejdbc.global.loggingSQLAndTime.enabled=true
scalikejdbc.global.loggingSQLAndTime.logLevel=info
scalikejdbc.global.loggingSQLAndTime.warningEnabled=true
scalikejdbc.global.loggingSQLAndTime.warningThresholdMillis=1000
scalikejdbc.global.loggingSQLAndTime.warningLogLevel=warn
# `true` on next line disables stack trace printout; see 'single line mode'
# here: http://scalikejdbc.org/documentation/query-inspector.html
scalikejdbc.global.loggingSQLAndTime.singleLineMode=true
scalikejdbc.global.loggingSQLAndTime.printUnprocessedStackTrace=false
scalikejdbc.global.loggingSQLAndTime.stackTraceDepth=10

Source code

Here’s the Scala source code that shows how to read from the kbhr and kbhr_geo_location databases:

import scalikejdbc._
import scalikejdbc.config._

object PopulateKbhrGeo1 extends App {

    // DBs.setup/DBs.setupAll loads specified JDBC driver classes.
    DBs.setupAll()
   
    // see http://scalikejdbc.org/documentation/operations.html for query examples
    // http://scalikejdbc.org/documentation/connection-pool.html (multiple db connections)
    println("RECORDS FROM KBHR")
    NamedDB('kbhr) readOnly { implicit session =>
        sql"select id from urls limit 2".foreach { rs =>
            println(rs.long("id"))
        }
    }

    println("RECORDS FROM KBHR_GEO")
    NamedDB('kbhr_geo) readOnly { implicit session =>
        sql"select ip_start from dbip_lookup limit 2".foreach { rs =>
            println(rs.long("ip_start"))
        }
    }

    // wipes out ConnectionPool
    DBs.closeAll()

}

More information

For more information, see these ScalikeJdbc links: