30

I want to know how can I do following things in scala?

  1. Connect to a postgreSQL database.
  2. Write SQL queries like SELECT , UPDATE etc. to modify a table in that database.

I know that in python I can do it using PygreSQL but how to do these things in scala?

7 Answers 7

21

You need to add dependency "org.postgresql" % "postgresql" % "9.3-1102-jdbc41" in build.sbt and you can modify following code to connect and query database. Replace DB_USER with your db user and DB_NAME as your db name.

import java.sql.{Connection, DriverManager, ResultSet}

object pgconn extends App {
  println("Postgres connector")

  classOf[org.postgresql.Driver]
  val con_st = "jdbc:postgresql://localhost:5432/DB_NAME?user=DB_USER"
  val conn = DriverManager.getConnection(con_str)
  try {
    val stm = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)

    val rs = stm.executeQuery("SELECT * from Users")

    while(rs.next) {
      println(rs.getString("quote"))
    }
 } finally {
     conn.close()
  }
}
17

I would recommend having a look at Doobie.

This chapter in the "Book of Doobie" gives a good sense of what your code will look like if you make use of this library.

This is the library of choice right now to solve this problem if you are interested in the pure FP side of Scala, i.e. scalaz, scalaz-stream (probably fs2 and cats soon) and referential transparency in general.

It's worth nothing that Doobie is NOT an ORM. At its core, it's simply a nicer, higher-level API over JDBC.

16

Take look at the tutorial "Using Scala with JDBC to connect to MySQL", replace the db url and add the right jdbc library. The link got broken so here's the content of the blog:

Using Scala with JDBC to connect to MySQL

A howto on connecting Scala to a MySQL database using JDBC. There are a number of database libraries for Scala, but I ran into a problem getting most of them to work. I attempted to use scala.dbc, scala.dbc2, Scala Query and Querulous but either they aren’t supported, have a very limited featured set or abstracts SQL to a weird pseudo language.

The Play Framework has a new database library called ANorm which tries to keep the interface to basic SQL but with a slight improved scala interface. The jury is still out for me, only used on one project minimally so far. Also, I’ve only seen it work within a Play app, does not look like it can be extracted out too easily.

So I ended up going with basic Java JDBC connection and it turns out to be a fairly easy solution.

Here is the code for accessing a database using Scala and JDBC. You need to change the connection string parameters and modify the query for your database. This example was geared towards MySQL, but any Java JDBC driver should work the same with Scala.

Basic Query

import java.sql.{Connection, DriverManager, ResultSet};

// Change to Your Database Config
val conn_str = "jdbc:mysql://localhost:3306/DBNAME?user=DBUSER&password=DBPWD"

// Load the driver
classOf[com.mysql.jdbc.Driver]

// Setup the connection
val conn = DriverManager.getConnection(conn_str)
try {
    // Configure to be Read Only
    val statement = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)

    // Execute Query
    val rs = statement.executeQuery("SELECT quote FROM quotes LIMIT 5")

    // Iterate Over ResultSet
    while (rs.next) {
        println(rs.getString("quote"))
    }
}
finally {
    conn.close
}

You will need to download the mysql-connector jar.

Or if you are using maven, the pom snippets to load the mysql connector, you’ll need to check what the latest version is.

<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.12</version>
</dependency>

To run the example, save the following to a file (query_test.scala) and run using, the following specifying the classpath to the connector jar:

scala -cp mysql-connector-java-5.1.12.jar:. query_test.scala

Insert, Update and Delete

To perform an insert, update or delete you need to create an updatable statement object. The execute command is slightly different and you will most likely want to use some sort of parameters. Here’s an example doing an insert using jdbc and scala with parameters.

// create database connection
val dbc = "jdbc:mysql://localhost:3306/DBNAME?user=DBUSER&password=DBPWD"
classOf[com.mysql.jdbc.Driver]
val conn = DriverManager.getConnection(dbc)
val statement = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)

// do database insert
try {
  val prep = conn.prepareStatement("INSERT INTO quotes (quote, author) VALUES (?, ?) ")
  prep.setString(1, "Nothing great was ever achieved without enthusiasm.")
  prep.setString(2, "Ralph Waldo Emerson")
  prep.executeUpdate
}
finally {
  conn.close
}
1
  • 23
    Wasn't the question how to connect to postgres sql? Sep 27, 2015 at 0:53
3

We are using Squeryl, which is working well so far for us. Depending on your needs it may do the trick.

Here is a list of supported DB's and the adapters

2

If you want/need to write your own SQL, but hate the JDBC interface, take a look at O/R Broker

2
  • 1
    That link is currently broken.
    – jedesah
    Jul 27, 2016 at 22:16
  • 2
    I wonder if SO offers a badge for "Broken link corrected after five or more years." I guess, the "Long-Term Maintenance" badge. Plus one. I would have called it the "Go for Broker."
    – som-snytt
    Jul 28, 2016 at 6:32
1

I would recommend the Quill query library. Here is an introduction post by Li Haoyi to get started.

TL;DR

{
    import io.getquill._
    import com.zaxxer.hikari.{HikariConfig, HikariDataSource}
    val pgDataSource = new org.postgresql.ds.PGSimpleDataSource()
    pgDataSource.setUser("postgres")
    pgDataSource.setPassword("example")
    val config = new HikariConfig()
    config.setDataSource(pgDataSource)
    val ctx = new PostgresJdbcContext(LowerCase, new HikariDataSource(config))
    import ctx._
}

Define a class ORM:

// mapping `city` table
case class City(
    id: Int,
    name: String,
    countryCode: String,
    district: String,
    population: Int
)

and query all items:

@ ctx.run(query[City])
cmd11.sc:1: SELECT x.id, x.name, x.countrycode, x.district, x.population FROM city x
val res11 = ctx.run(query[City])
                   ^

res11: List[City] = List(
  City(1, "Kabul", "AFG", "Kabol", 1780000),
  City(2, "Qandahar", "AFG", "Qandahar", 237500),
  City(3, "Herat", "AFG", "Herat", 186800),
...
0

ScalikeJDBC is quite easy to use. It allows you to write raw SQL using interpolated strings.

http://scalikejdbc.org/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.