0PricingLogin
Scala for Backend Engineering & Functional Programming · Lesson

Inserts and Updates

Write data functionally.

Update0 for Writes

Writes use the same sql interpolator, but you call .update to get an Update0 instead of .query.

Running .run on an Update0 returns a ConnectionIO[Int]: the number of affected rows.

import doobie.implicits._

def insert(name: String, age: Int): ConnectionIO[Int] =
  sql"insert into users (name, age) values ($name, $age)".update.run

Affected Row Counts

The Int from .run is the JDBC update count. For an UPDATE or DELETE it tells you how many rows matched.

You can branch on it to detect, for example, an update that matched no rows.

def deactivate(id: Long): ConnectionIO[Int] =
  sql"update users set active = false where id = $id".update.run

All lessons in this course

  1. Connecting with a Transactor
  2. Running Queries
  3. Inserts and Updates
  4. Composing Transactions
← Back to Scala for Backend Engineering & Functional Programming