JDBC query
Stay organized with collections
Save and categorize content based on your preferences.
Run a query by using JDBC.
Explore further
For detailed documentation that includes this code sample, see the following:
Code sample
Java
To learn how to install and use the client library for Spanner, see Spanner client libraries.
To authenticate to Spanner, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.
importjava.sql.Connection;
importjava.sql.DriverManager;
importjava.sql.ResultSet;
importjava.sql.SQLException;
importjava.sql.Statement;
publicclass SingleUseReadOnlyExample{
staticvoidsingleUseReadOnly()throwsSQLException{
// TODO(developer): Replace these variables before running the sample.
StringprojectId="my-project";
StringinstanceId="my-instance";
StringdatabaseId="my-database";
singleUseReadOnly(projectId,instanceId,databaseId);
}
staticvoidsingleUseReadOnly(StringprojectId,StringinstanceId,StringdatabaseId)
throwsSQLException{
StringconnectionUrl=
String.format(
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
projectId,instanceId,databaseId);
try(Connectionconnection=DriverManager.getConnection(connectionUrl);
Statementstatement=connection.createStatement()){
// When the connection is in autocommit mode, any query that is executed will automatically
// be executed using a single-use read-only transaction, even if the connection itself is in
// read/write mode.
try(ResultSetrs=
statement.executeQuery(
"SELECT SingerId, FirstName, LastName, Revenues FROM Singers ORDER BY LastName")){
while(rs.next()){
System.out.printf(
"%d %s %s %s%n",
rs.getLong(1),rs.getString(2),rs.getString(3),rs.getBigDecimal(4));
}
}
}
}
}
What's next
To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.