-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJdbcExample.scala
73 lines (58 loc) · 2.54 KB
/
JdbcExample.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.example.scleradb.jdbc
import java.util.Properties
import java.sql.{Connection, Statement, ResultSet}
import java.sql.{DriverManager, ResultSetMetaData}
object JdbcExample {
val jdbcUrl: String = "jdbc:scleradb"
def main(args: Array[String]): Unit = args match {
case Array("--init") => initialize() // initialize Sclera
case queries => runQueries(queries) // execute queries
}
// initialize Sclera
private def initialize(): Unit = {
// we are initializing the schema, no need to check and validate
val props: Properties = new Properties()
props.setProperty("checkSchema", "false")
// get a JDBC connection to Sclera
val conn: Connection = DriverManager.getConnection(jdbcUrl, props)
try {
// display warnings, if any
Option(conn.getWarnings()).foreach(println)
// initialize the schema by executing the statement "create schema"
val stmt: Statement = conn.createStatement()
try stmt.executeUpdate("create schema") finally stmt.close()
} finally conn.close()
}
// run queries on Sclera
private def runQueries(queries: Array[String]): Unit = {
// get a JDBC connection to Sclera
val conn: Connection = DriverManager.getConnection(jdbcUrl)
try {
// display warnings, if any
Option(conn.getWarnings()).foreach(println)
// create a statement to execute queries
val stmt: Statement = conn.createStatement()
// iterate over the input queries
try queries.foreach { query =>
// execute query
val rs: ResultSet = stmt.executeQuery(query)
try {
// result metadata
val metaData: ResultSetMetaData = rs.getMetaData()
val n: Int = metaData.getColumnCount()
val colNames: Seq[String] = Range.inclusive(1, n).map { i =>
metaData.getColumnLabel(i)
}
// display column names
println(colNames.mkString(", "))
// display each row in the result
while( rs.next() ) {
val rowVals: Seq[String] =
Range.inclusive(1, n).map { i => rs.getString(i) }
println(rowVals.mkString(", "))
}
} finally rs.close()
} finally stmt.close()
} finally conn.close()
}
}