This module contains functions to access relational databases from XQuery using SQL. With this module, you can execute query, update and prepared statements, and the result sets are returned as sequences of XML elements representing tuples. Each element has children representing the columns returned by the SQL statement.
This module uses JDBC to connect to a SQL server. Hence, your JDBC driver will need to be added to the classpath, too. If you work with the full distributions of BaseX, you can copy the driver into the lib/custom directory. JDBC drivers are available for many relational databases, for example:
All functions and errors are in the http://basex.org/modules/sql namespace, to which the sql prefix is statically bound.
| Signature | sql:init(
$class as xs:string
) as empty-sequence() |
|---|
| Summary | This function initializes a JDBC driver specified via $class. This step might be superfluous if the SQL database is not embedded. |
|---|
| Errors | init | A database driver is not found. |
|
|---|
| Signature | sql:connect(
$url as xs:string,
$username as xs:string? := (),
$password as xs:string? := (),
$options as map(*)? := {}
) as xs:anyURI |
|---|
| Summary | This function establishes a connection to a relational database and returns a connection id. The parameter $url is the URL of the database and shall be of the form: jdbc:<driver name>:[//<server>[/<database>]]. Values specified for $username and $password are used as credentials for connecting to the database. The $options parameter can be used to set connection options. |
|---|
| Errors | error | An SQL exception occurred. |
|
|---|
| Examples | sql:connect('jdbc:sqlserver://DBServer', { 'autocommit': true() }) Connects to an SQL Server and sets autocommit to true. |
|---|
| Signature | sql:execute(
$id as xs:anyURI,
$statement as xs:string,
$options as map(*)? := {}
) as item()* |
|---|
| Summary | This function executes an SQL $statement, using the connection with the specified $id. The returned result depends on the kind of statement:
- If an update statement was executed, the number of updated rows will be returned as integer.
- Otherwise, an XML representation of all results will be returned.
The following $options are available:
| option | default | description |
|---|
timeout | – |
Query execution will be interrupted after the specified number of seconds.
| generated-keys | false |
If enabled, an updating statement returns the auto-generated keys (e.g. the values of an auto-increment column) as <sql:row/> elements instead of the number of updated rows. The statement must be run against a driver that supports this optional JDBC feature. For drivers that support the SQL RETURNING clause (e.g. PostgreSQL, SQLite, MariaDB), appending RETURNING … to an updating statement returns the affected rows directly and is usually preferable to this option.
| null | false |
By default, columns with NULL values are omitted from the result. If enabled, they are represented as empty columns with a null attribute: <sql:column name="…" null="true"/>.
|
|
|---|
| Errors | error | An SQL exception occurred. | id | A connection does not exist. | timeout | Query execution exceeded timeout. |
|
|---|
Added: New function.
| Signature | sql:execute-batch(
$id as xs:anyURI,
$params as (element(sql:parameters)|array(*))* := (),
$options as map(*)? := {}
) as xs:integer* |
|---|
| Summary | This function executes a prepared statement with the specified $id once for each parameter set in $params, as a single JDBC batch, and returns the update counts of all executions. Each item of $params is one parameter set, specified in either of the forms accepted by sql:execute-prepared (an array(*) or a <sql:parameters/> element). This is considerably faster than calling sql:execute-prepared in a loop. The connection's driver must support JDBC batch updates.
The following $options are available:
| option | default | description |
|---|
timeout | – |
Query execution will be interrupted after the specified number of seconds.
|
|
|---|
| Errors | error | An SQL exception occurred. | id | A connection does not exist. | timeout | Query execution exceeded timeout. |
|
|---|
| Examples | let $conn := sql:connect("jdbc:postgresql://localhost:5432/coffeehouse")
let $prep := sql:prepare($conn, "INSERT INTO coffees (name, price) VALUES (?, ?)")
return sql:execute-batch($prep, (
[ "Espresso", 2.5e0 ],
[ "Latte", 3.0e0 ],
[ "Mocha", 3.5e0 ]
)) Inserts three rows in a single batch and returns their update counts. |
|---|
| Signature | sql:execute-prepared(
$id as xs:anyURI,
$params as (element(sql:parameters)|array(*))? := (),
$options as map(*)? := {}
) as item()* |
|---|
| Summary | This function executes a prepared statement with the specified $id. The output format is identical to sql:execute.
The optional parameter $params supplies the values for the ? placeholders of the prepared statement, in order. It can be specified in two ways: - As an array: each array member supplies one positional parameter; its SQL type is derived from the XDM type of the value (e.g.
xs:integer, xs:double, xs:boolean, xs:date), and an empty sequence is bound to NULL. This is the recommended form:
sql:execute-prepared($prep, [ 10, 'French_Roast' ])
- As an element
<sql:parameters/>, with explicit types and values. The following schema shall be used:
element sql:parameters {
element sql:parameter {
attribute type {
"bigdecimal" | "boolean" | "byte" | "date" | "double" | "float" |
"int" | "long" | "short" | "sqlxml" | "string" | "time" | "timestamp"
},
attribute null { "true" | "false" }?,
text
}+
}?
The following $options are available:
| option | default | description |
|---|
timeout | – |
Query execution will be interrupted after the specified number of seconds.
| null | false |
By default, columns with NULL values are omitted from the result. If enabled, they are represented as empty columns with a null attribute: <sql:column name="…" null="true"/>.
|
|
|---|
| Errors | attribute | An attribute different from type and null is set for a <sql:parameter/> element. | error | An SQL exception occurred. | id | A connection does not exist. | parameters | No parameter type specified. | timeout | Query execution exceeded timeout. | type | The value of a parameter cannot be converted to the specified format. |
|
|---|
| Signature | sql:prepare(
$id as xs:anyURI,
$statement as xs:string,
$options as map(*)? := {}
) as xs:anyURI |
|---|
| Summary | This function prepares an SQL $statement, using the specified connection $id, and returns the id reference to this statement. The statement is a string with one or more '?' placeholders. If the value of a field has to be set to NULL, then the attribute null of the <sql:parameter/> element must be true.
The following $options are available:
| option | default | description |
|---|
generated-keys | false |
If enabled, an updating statement executed via sql:execute-prepared returns its auto-generated keys (e.g. the values of an auto-increment column) as <sql:row/> elements instead of the number of updated rows. The connection's driver must support this optional JDBC feature. For drivers that support the SQL RETURNING clause (e.g. PostgreSQL, SQLite, MariaDB), appending RETURNING … to the prepared statement returns the affected rows directly and is usually preferable to this option.
|
|
|---|
| Errors | error | An SQL exception occurred. | id | A connection does not exist. |
|
|---|
| Signature | sql:commit(
$id as xs:anyURI
) as empty-sequence() |
|---|
| Summary | This function commits the changes made to a relational database, using the specified connection $id. |
|---|
| Errors | error | An SQL exception occurred. | id | A connection does not exist. |
|
|---|
| Signature | sql:rollback(
$id as xs:anyURI
) as empty-sequence() |
|---|
| Summary | This function rolls back the changes made to a relational database, using the specified connection $id. |
|---|
| Errors | error | An SQL exception occurred. | id | A connection does not exist. |
|
|---|
| Signature | sql:close(
$id as xs:anyURI
) as empty-sequence() |
|---|
| Summary | This function closes a database connection with the specified $id. Opened connections will automatically be closed after the XQuery expression has been evaluated, but in order to save memory, it is always recommended to close connections that are not used anymore. |
|---|
| Errors | error | An SQL exception occurred. | id | A connection does not exist. |
|
|---|
A simple select statement can be executed as follows:
let $id := sql:connect("jdbc:postgresql://localhost:5432/coffeehouse")
return sql:execute($id, "SELECT * FROM coffees WHERE price < 10")
The result may look like:
<sql:row xmlns:sql="http://basex.org/modules/sql">
<sql:column name="cof_name">French_Roast</sql:column>
<sql:column name="sup_id">49</sql:column>
<sql:column name="price">3.5</sql:column>
<sql:column name="sales">15</sql:column>
<sql:column name="total">30</sql:column>
</sql:row>
<sql:row xmlns:sql="http://basex.org/modules/sql">
<sql:column name="cof_name">French_Roast_Decaf</sql:column>
<sql:column name="sup_id">49</sql:column>
<sql:column name="price">7.5</sql:column>
<sql:column name="sales">10</sql:column>
<sql:column name="total">14</sql:column>
</sql:row>
A prepared select statement can be executed in the following way:
(: Establish a connection :)
let $conn := sql:connect("jdbc:postgresql://localhost:5432/coffeehouse")
(: Obtain a handle to a prepared statement :)
let $prep := sql:prepare($conn, "SELECT * FROM coffees WHERE price < ? AND cof_name = ?")
(: Values and types of prepared statement parameters :)
let $params := <sql:parameters>
<sql:parameter type='double'>10</sql:parameter>
<sql:parameter type='string'>French_Roast</sql:parameter>
</sql:parameters>
(: Execute prepared statement :)
return sql:execute-prepared($prep, $params)
The same parameters can be supplied more concisely as an array, with the SQL types inferred from the values:
let $conn := sql:connect("jdbc:postgresql://localhost:5432/coffeehouse")
let $prep := sql:prepare($conn, "SELECT * FROM coffees WHERE price < ? AND cof_name = ?")
return sql:execute-prepared($prep, [ 10e0, 'French_Roast' ])
The following expression demonstrates how SQLite can be addressed:
(: Initialize driver :)
sql:init("org.sqlite.JDBC"),
(: Establish a connection :)
let $conn := sql:connect("jdbc:sqlite:database.db")
return (
(: Create a new table :)
sql:execute($conn, "drop table if exists person"),
sql:execute($conn, "create table person (id integer, name string)"),
(: Run 10 updates :)
for $i in 1 to 10
let $q := "insert into person values(" || $i || ", '" || $i || "')"
return sql:execute($conn, $q),
(: Return table contents :)
sql:execute($conn, "select * from person")
)
| Code | Description |
|---|
attribute | An attribute different from type and null is set for a <sql:parameter/> element. |
error | An SQL exception occurred. |
id | A connection does not exist. |
init | A database driver is not found. |
parameters | No parameter type specified. |
timeout | Query execution exceeded timeout. |
type | The value of a parameter cannot be converted to the specified format. |
Version 13Version 11- Updated:
sql:connect: Credentials have become optional.
Version 9.6Version 9.0- Updated:
sql:execute, sql:execute-prepared: Return update count for updating statements. $options argument added. - Updated: Connection ids are URIs now.
- Updated: error codes updated; errors now use the module namespace
Version 7.5Version 7.0