This page shows you how to perform basic operations in Spanner using the Spanner JDBC driver.
Install the JDBC driver
Follow the steps in Spanner client libraries
to set up authentication, and then add the Spanner JDBC driver
dependencies, shown in the following snippet, to your pom.xml
file.
In case you are using a framework that requires the Java class name in order to load the JDBC driver, it is
com.google.cloud.spanner.jdbc.JdbcDriver
. See
the API documentation for JdbcDriver
for how to set up a connection.
Connect to a Spanner database
The JdbcDriver class description shows the connection string syntax and includes sample code to create a connection and run a query.
The driver automatically detects the SQL dialect (GoogleSQL or PostgreSQL) of the specified database. A dialect parameter is not required or allowed.
Connect to the emulator
To connect to the emulator, set the
SPANNER_EMULATOR_HOST
environment variable, for example:
Linux / macOS
export SPANNER_EMULATOR_HOST=localhost:9010
Windows
set SPANNER_EMULATOR_HOST=localhost:9010
This instructs the Spanner JDBC driver driver to connect to the
emulator running on the localhost
instead of the default production service.
Examples
The following code examples cover some common use cases.
Run a schema update
The following code example adds the Singers
table to the database by first
creating a JDBC connection and then creating the table:
Use a transaction in autocommit mode to add rows
If you don't need to commit multiple operations as a group, you can use a
transaction in autocommit mode, which is the default behavior. The following code
example uses a transaction in autocommit mode to add rows to the Singers
table:
Control how multiple operations are committed as a group
If you want to control whether Spanner commits multiple operations
together as a group, you can disable autocommit mode. The
following code example uses connection.setAutoCommit(false)
and
connection.commit()
to add rows to the Singers
table.
Run a SQL query
The following code example returns all rows in the Singers
table ordered by the
singer's last name:
What's next
- Get answers to frequently asked questions about the Spanner JDBC driver.
- Learn about the Spanner JDBC driver session management commands.