Compdigitec Labs

« | Home | »

Accessing SQL databases from Scala

By admin | July 21, 2021

import scalikejdbc._
import scalikejdbc.scalikejdbcSQLInterpolationImplicitDef

// initialize JDBC driver & connection pool
Class.forName("org.postgresql.Driver")

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

sql"""
create table members (
  id serial not null primary key,
  fav_num integer NOT NULL,
  name text NOT NULL
)
""".execute.apply()(scalikejdbc.AutoSession)

sql"""
INSERT INTO members (name, fav_num) VALUES ('Foo', 123)
""".execute.apply()(scalikejdbc.AutoSession)

sql"""
INSERT INTO members (name, fav_num) VALUES ('Bar', 456)
""".execute.apply()(scalikejdbc.AutoSession)

// http://scalikejdbc.org/documentation/operations.html
scalikejdbc.DB.readOnly { implicit session =>
  sql"select * from members".foreach { (rs: scalikejdbc.WrappedResultSet) =>
    println(rs.toMap())
  }
}

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
\dt
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. pg slot ฝาก 50 รับ 100 Says:
    June 23rd, 2022 at 10:45

    pg slot ฝาก 50 รับ 100 ต้นแบบให้เลือกรับ โดยจะมีการเปลี่ยนแปลงไปเรื่องๆจะเปิดตามโอกาศ หรือกิจกรรมต่างๆกับเว็บไซต์ของพวกเรา พีจีสล็อต ที่จะให้แก่คุณบันเทิงใจกับเกมสล็อต PG

Comments