使用 JDBC 运行查询。
包含此代码示例的文档页面
如需查看上下文中使用的代码示例,请参阅以下文档:
代码示例
Java
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SingleUseReadOnlyExample {
static void singleUseReadOnly() throws SQLException {
// TODO(developer): Replace these variables before running the sample.
String projectId = "my-project";
String instanceId = "my-instance";
String databaseId = "my-database";
singleUseReadOnly(projectId, instanceId, databaseId);
}
@SuppressFBWarnings(
value = "OBL_UNSATISFIED_OBLIGATION",
justification = "https://github.com/spotbugs/spotbugs/issues/293")
static void singleUseReadOnly(String projectId, String instanceId, String databaseId)
throws SQLException {
String connectionUrl =
String.format(
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
projectId, instanceId, databaseId);
try (Connection connection = DriverManager.getConnection(connectionUrl);
Statement statement = 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 (ResultSet rs =
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));
}
}
}
}
}