Tetap teratur dengan koleksi
Simpan dan kategorikan konten berdasarkan preferensi Anda.
Halaman ini menunjukkan cara menjalankan operasi dasar di Spanner menggunakan
driver JDBC Spanner.
Menginstal driver JDBC
Ikuti langkah-langkah di library klien Spanner
untuk menyiapkan autentikasi, lalu tambahkan dependensi driver JDBC Spanner, yang ditampilkan dalam cuplikan berikut, ke file pom.xml Anda.
Jika Anda menggunakan framework yang memerlukan nama class Java agar dapat
memuat driver JDBC, kodenya adalah com.google.cloud.spanner.jdbc.JdbcDriver. Lihat
dokumentasi API untuk JdbcDriver
guna mengetahui cara menyiapkan koneksi.
Menghubungkan ke database Spanner
Deskripsi class JdbcDriver
menampilkan sintaksis string koneksi dan menyertakan contoh kode untuk
membuat koneksi dan menjalankan kueri.
Driver otomatis mendeteksi dialek SQL (GoogleSQL atau PostgreSQL)
dari database yang ditentukan. Parameter dialek tidak diperlukan atau diizinkan.
Menghubungkan ke emulator
Untuk terhubung ke emulator, tetapkan
variabel lingkungan SPANNER_EMULATOR_HOST, misalnya:
Linux / Mac
export SPANNER_EMULATOR_HOST=localhost:9010
Windows
set SPANNER_EMULATOR_HOST=localhost:9010
Tindakan ini akan menginstruksikan driver driver JDBC Spanner untuk terhubung ke
emulator yang berjalan di localhost, bukan layanan produksi default.
Contoh
Contoh kode berikut mencakup beberapa kasus penggunaan umum.
Menjalankan update skema
Contoh kode berikut menambahkan tabel Singers ke database dengan terlebih dahulu membuat koneksi JDBC, lalu membuat tabel:
Menggunakan transaksi dalam mode autocommit untuk menambahkan baris
Jika tidak perlu meng-commit beberapa operasi sebagai grup, Anda dapat menggunakan transaksi dalam mode autocommit, yang merupakan perilaku default. Contoh kode berikut
menggunakan transaksi dalam mode autocommit untuk menambahkan baris ke tabel Singers:
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Arrays;
import java.util.List;
class InsertDataExample {
// Class to contain singer sample data.
static class Singer {
final long singerId;
final String firstName;
final String lastName;
final BigDecimal revenues;
Singer(long singerId, String firstName, String lastName, BigDecimal revenues) {
this.singerId = singerId;
this.firstName = firstName;
this.lastName = lastName;
this.revenues = revenues;
}
}
static final List<Singer> SINGERS =
Arrays.asList(
new Singer(10, "Marc", "Richards", new BigDecimal("104100.00")),
new Singer(20, "Catalina", "Smith", new BigDecimal("9880.99")),
new Singer(30, "Alice", "Trentor", new BigDecimal("300183")),
new Singer(40, "Lea", "Martin", new BigDecimal("20118.12")),
new Singer(50, "David", "Lomond", new BigDecimal("311399.26")));
static void insertData() throws SQLException {
// TODO(developer): Replace these variables before running the sample.
String projectId = "my-project";
String instanceId = "my-instance";
String databaseId = "my-database";
insertData(projectId, instanceId, databaseId);
}
static void insertData(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)) {
try (PreparedStatement ps =
connection.prepareStatement(
"INSERT INTO Singers\n"
+ "(SingerId, FirstName, LastName, SingerInfo, Revenues)\n"
+ "VALUES\n"
+ "(?, ?, ?, ?, ?)")) {
for (Singer singer : SINGERS) {
ps.setLong(1, singer.singerId);
ps.setString(2, singer.firstName);
ps.setString(3, singer.lastName);
ps.setNull(4, Types.BINARY);
ps.setBigDecimal(5, singer.revenues);
ps.addBatch();
}
int[] updateCounts = ps.executeBatch();
System.out.printf("Insert counts: %s%n", Arrays.toString(updateCounts));
}
}
}
}
Mengontrol cara beberapa operasi dilakukan sebagai grup
Jika ingin mengontrol apakah Spanner melakukan commit beberapa operasi
bersama sebagai satu grup, Anda dapat menonaktifkan mode autocommit. Contoh
kode berikut menggunakan connection.setAutoCommit(false) dan
connection.commit() untuk menambahkan baris ke tabel Singers.
import com.google.common.collect.ImmutableList;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
class BatchDmlExample {
static class Singer {
final long singerId;
final String firstName;
final String lastName;
final BigDecimal revenues;
Singer(long singerId, String firstName, String lastName, BigDecimal revenues) {
this.singerId = singerId;
this.firstName = firstName;
this.lastName = lastName;
this.revenues = revenues;
}
}
static void batchDml() throws SQLException {
// TODO(developer): Replace these variables before running the sample.
String projectId = "my-project";
String instanceId = "my-instance";
String databaseId = "my-database";
batchDml(projectId, instanceId, databaseId);
}
// This example shows how to execute a batch of DML statements with the JDBC driver.
static void batchDml(String projectId, String instanceId, String databaseId) throws SQLException {
String connectionUrl =
String.format(
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
projectId, instanceId, databaseId);
ImmutableList<Singer> singers = ImmutableList.of(
new Singer(10, "Marc", "Richards", BigDecimal.valueOf(10000)),
new Singer(11, "Amirah", "Finney", BigDecimal.valueOf(195944.10d)),
new Singer(12, "Reece", "Dunn", BigDecimal.valueOf(10449.90))
);
try (Connection connection = DriverManager.getConnection(connectionUrl)) {
connection.setAutoCommit(false);
// Use prepared statements for the lowest possible latency when executing the same SQL string
// multiple times.
try (PreparedStatement statement = connection.prepareStatement(
"INSERT INTO Singers (SingerId, FirstName, LastName, Revenues)\n"
+ "VALUES (?, ?, ?, ?)")) {
for (Singer singer : singers) {
statement.setLong(1, singer.singerId);
statement.setString(2, singer.firstName);
statement.setString(3, singer.lastName);
statement.setBigDecimal(4, singer.revenues);
// Add the current parameter values to the batch.
statement.addBatch();
}
// Execute the batched statements.
int[] updateCounts = statement.executeBatch();
connection.commit();
System.out.printf("Batch insert counts: %s%n", Arrays.toString(updateCounts));
}
}
}
}
Menjalankan kueri SQL
Contoh kode berikut menampilkan semua baris dalam tabel Singers yang diurutkan berdasarkan nama belakang penyanyi:
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);
}
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));
}
}
}
}
}
[[["Mudah dipahami","easyToUnderstand","thumb-up"],["Memecahkan masalah saya","solvedMyProblem","thumb-up"],["Lainnya","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Masalah terjemahan","translationIssue","thumb-down"],["Lainnya","otherDown","thumb-down"]],["Terakhir diperbarui pada 2024-04-10 UTC."],[],[]]