-
Notifications
You must be signed in to change notification settings - Fork 0
/
YBCqlHelloWorld.scala
72 lines (61 loc) · 2.01 KB
/
YBCqlHelloWorld.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
package com.yugabyte.sample.apps
import com.datastax.driver.core.Cluster
import com.datastax.driver.core.ResultSet
import com.datastax.driver.core.Row
import com.datastax.driver.core.Session
object YBCqlHelloWorld {
def main(args: Array[String]): Unit = {
try {
// Create a Cassandra client.
val cluster = Cluster.builder.addContactPoint("127.0.0.1").build
val session = cluster.connect
// Create keyspace 'ybdemo' if it does not exist.
val createKeyspace = "CREATE KEYSPACE IF NOT EXISTS ybdemo;";
val createKeyspaceResult = session.execute(createKeyspace);
println("Created keyspace ybdemo");
// Create table 'employee' if it does not exist.
val createTable = """
CREATE TABLE IF NOT EXISTS ybdemo.employee (
id int PRIMARY KEY,
name varchar,
age int,
language varchar
);
"""
val createResult = session.execute(createTable)
println("Created table employee")
// Insert a row.
val insert = """
INSERT INTO ybdemo.employee
|(id, name, age, language)
|VALUES
|(1, 'John', 35, 'Scala');
""".trim.stripMargin('|').replaceAll("\n", " ")
val insertResult = session.execute(insert)
println(s"Inserted data: ${insert}")
// Query the row and print out the result.
val select = """
SELECT name, age, language
FROM ybdemo.employee
WHERE id = 1;
"""
val rows = session.execute(select).all
val name = rows.get(0).getString(0)
val age = rows.get(0).getInt(1)
val language = rows.get(0).getString(2)
println(
s"""
Query returned ${rows.size}
|row: name=${name},
|age=${age},
|language=${language}
""".trim.stripMargin('|').replaceAll("\n", " ")
)
// Close the client.
session.close
cluster.close
} catch {
case e: Throwable => println(e.getMessage)
}
} // def main
} // object YBCqlHelloWorld