Use the Polypheny JDBC driver from Scala. These Scala 2.13 examples use Using.Manager to close JDBC resources when leaving the block, including on failure.
Set up the project
Use JDK 17, Gradle 8.10, and a running Polypheny instance with the Prism 2.2 query interface enabled. The examples use port 20590 and the local default credentials pa with an empty password.
In a new project directory, create an empty settings.gradle. Add the project configuration below to build.gradle.
plugins {
id 'scala'
id 'application'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.scala-lang:scala-library:2.13.17'
implementation 'org.polypheny:polypheny-jdbc-driver:3.1'
}
application {
mainClass = 'PolyphenyExample'
}
Run SQL and read metadata
Save this program as src/main/scala/PolyphenyExample.scala.
import java.sql.DriverManager
import scala.util.Using
object PolyphenyExample {
def main(args: Array[String]): Unit = {
val url = "jdbc:polypheny://localhost:20590/"
Using.Manager { use =>
val connection = use(DriverManager.getConnection(url, "pa", ""))
val statement = use(connection.prepareStatement("SELECT CAST(? AS VARCHAR(32)) AS product"))
statement.setString(1, "Keyboard")
val rows = use(statement.executeQuery())
while (rows.next()) {
println(rows.getString("product"))
}
val schemas = use(connection.getMetaData.getSchemas)
while (schemas.next()) {
println(schemas.getString("TABLE_SCHEM"))
}
}.get
}
}
Run it from the project directory.
gradle run
It prints Keyboard followed by the server’s visible schema names. Supply query values through the prepared statement to keep them separate from the SQL text.
Query a document collection
Create a document namespace named docs_jdbc_catalog. In a MongoQL console for that namespace, create the collection and add a document.
db.createCollection("products");
db.products.insertOne({name: "Keyboard", inStock: true});
Replace src/main/scala/PolyphenyExample.scala with this program and run gradle run again.
import java.sql.DriverManager
import org.polypheny.jdbc.PolyConnection
import org.polypheny.jdbc.multimodel.DocumentResult
import scala.jdk.CollectionConverters._
import scala.util.Using
object PolyphenyExample {
def main(args: Array[String]): Unit = {
val url = "jdbc:polypheny://localhost:20590/"
Using.Manager { use =>
val connection = use(DriverManager.getConnection(url, "pa", ""))
val statement = connection.unwrap(classOf[PolyConnection]).createPolyStatement()
val result = statement
.execute("docs_jdbc_catalog", "mongo", "db.products.find({inStock: true})")
.asInstanceOf[DocumentResult]
for (document <- result.asScala) {
println(document.get("name").asString())
}
}.get
}
}
asScala adapts the JDBC extension’s Java iterable to Scala. Iterate within the Using block so the connection stays open as results are fetched. See the JDBC multi-model extensions for the other result types.