Connessione ad H2 in Scala
H2 è un database portatile molto usato in ambito Java.
In questo articolo vediamo come usarlo con Scala.
Prima di tutto installiamo la dipendenza.
Se usate sbt:
libraryDependencies ++= Seq(
"com.h2database" % "h2" % "2.3.232"
)
Qui sotto un codice di esempio in cui:
- creiamo il db e la tabella
- aggiungiamo dei records
- leggiamo i records
package com.test
import java.sql.{Connection, DriverManager, ResultSet, Timestamp}
import java.util.Calendar
@main
def main(): Unit = {
Class.forName("org.h2.Driver")
val conn: Connection = DriverManager.getConnection("jdbc:h2:./DATABASE/my_db", "", "")
createDb(conn)
insertData(conn)
selectData(conn)
conn.close()
}
def createDb(conn: Connection): Unit = {
val sql =
"""
CREATE SCHEMA IF NOT EXISTS my_db;
SET SCHEMA my_db;
CREATE TABLE IF NOT EXISTS operation_log (id INT AUTO_INCREMENT PRIMARY KEY, operation VARCHAR(255), date TIMESTAMP);
"""
val stmt = conn.createStatement()
stmt.execute(sql)
stmt.close()
}
def insertData(conn: Connection): Unit = {
val sql = "INSERT INTO operation_log (operation, date) VALUES (?, ?)"
val stmt = conn.prepareStatement(sql)
stmt.setString(1, "prova")
stmt.setTimestamp(2, new Timestamp(Calendar.getInstance().getTime.getTime))
stmt.executeUpdate()
stmt.close()
}
def selectData(conn: Connection): Unit = {
val sql = "SELECT * FROM operation_log"
val stmt = conn.prepareStatement(sql)
val res: ResultSet = stmt.executeQuery()
while ( {
res.next
}) {
val id = res.getInt("id")
val operation = res.getString("operation")
val dtm = res.getTimestamp("date")
println(id + " " + operation + " " + dtm.toString)
}
stmt.close()
}
Vi lascio le altre operazioni come esercizio.
Enjoy!
scala sbt database h2
Commentami!