Compdigitec Labs

« | Home | »

Accessing SQL databases from Scala

By admin | July 21, 2021

import scalikejdbc._
import scalikejdbc.scalikejdbcSQLInterpolationImplicitDef

// initialize JDBC driver & connection pool

scalikejdbc.ConnectionPool.singleton("jdbc:postgresql://localhost:5432/", "user", "abcdef888")

create table members (
  id serial not null primary key,
  fav_num integer NOT NULL,
  name text NOT NULL

INSERT INTO members (name, fav_num) VALUES ('Foo', 123)

INSERT INTO members (name, fav_num) VALUES ('Bar', 456)

scalikejdbc.DB.readOnly { implicit session =>
  sql"select * from members".foreach { (rs: scalikejdbc.WrappedResultSet) =>

You can run the database with Docker (example) as follows:

docker run --name mypsql -e POSTGRES_USER=user -e POSTGRES_PASSWORD=abcdef888 -p 5432:5432 postgres:13.3

Reference instructions for connecting to the docker instance:

psql -h localhost -U user
select * from members;

If you found this article helpful or interesting, please help Compdigitec spread the word. Don’t forget to subscribe to Compdigitec Labs for more useful and interesting articles!

Topics: Code | 1 Comment »

One Response to “Accessing SQL databases from Scala”

  1. Harry Says:
    August 16th, 2023 at 05:43

    It helped me in my coding thanks.