« Local build in npm | Home | Serving VNC via HTML5 using noVNC and x11vnc »
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 »
August 16th, 2023 at 05:43
It helped me in my coding thanks.