-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathJdbcSample.java
1830 lines (1735 loc) · 66.6 KB
/
JdbcSample.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.spanner.jdbc;
import com.google.api.gax.core.NoCredentialsProvider;
import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;
import com.google.cloud.spanner.DatabaseId;
import com.google.cloud.spanner.Mutation;
import com.google.cloud.spanner.SpannerExceptionFactory;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.admin.database.v1.DatabaseAdminClient;
import com.google.cloud.spanner.admin.database.v1.DatabaseAdminSettings;
import com.google.cloud.spanner.jdbc.CloudSpannerJdbcConnection;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.spanner.admin.database.v1.CreateDatabaseRequest;
import com.google.spanner.admin.database.v1.DatabaseDialect;
import com.google.spanner.admin.instance.v1.InstanceName;
import com.google.spanner.v1.DatabaseName;
import io.grpc.ManagedChannelBuilder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
public final class JdbcSample {
static class Singer {
/** Primary key in the Singers table. */
private final long singerId;
/** Mapped to the FirstName column. */
private final String firstName;
/** Mapped to the FirstName column. */
private final String lastName;
Singer(final long id, final String first, final String last) {
this.singerId = id;
this.firstName = first;
this.lastName = last;
}
public long getSingerId() {
return singerId;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}
static class Album {
/** The first part of the primary key of Albums. */
private final long singerId;
/** The second part of the primary key of Albums. */
private final long albumId;
/** Mapped to the AlbumTitle column. */
private final String albumTitle;
Album(final long singer, final long album, final String title) {
this.singerId = singer;
this.albumId = album;
this.albumTitle = title;
}
public long getSingerId() {
return singerId;
}
public long getAlbumId() {
return albumId;
}
public String getAlbumTitle() {
return albumTitle;
}
}
// [START spanner_insert_data]
// [START spanner_postgresql_insert_data]
/** The list of Singers to insert. */
static final List<Singer> SINGERS =
Arrays.asList(
new Singer(1, "Marc", "Richards"),
new Singer(2, "Catalina", "Smith"),
new Singer(3, "Alice", "Trentor"),
new Singer(4, "Lea", "Martin"),
new Singer(5, "David", "Lomond"));
/** The list of Albums to insert. */
static final List<Album> ALBUMS =
Arrays.asList(
new Album(1, 1, "Total Junk"),
new Album(1, 2, "Go, Go, Go"),
new Album(2, 1, "Green"),
new Album(2, 2, "Forever Hold Your Peace"),
new Album(2, 3, "Terrified"));
// [END spanner_insert_data]
// [END spanner_postgresql_insert_data]
private JdbcSample() {
}
// [START spanner_create_database]
static void createDatabase(
final DatabaseAdminClient dbAdminClient,
final InstanceName instanceName,
final String databaseId,
final Properties properties) throws SQLException {
// Use the Spanner admin client to create a database.
CreateDatabaseRequest createDatabaseRequest =
CreateDatabaseRequest.newBuilder()
.setCreateStatement("CREATE DATABASE `" + databaseId + "`")
.setParent(instanceName.toString())
.build();
try {
dbAdminClient.createDatabaseAsync(createDatabaseRequest).get();
} catch (ExecutionException e) {
throw SpannerExceptionFactory.asSpannerException(e.getCause());
} catch (InterruptedException e) {
throw SpannerExceptionFactory.propagateInterrupt(e);
}
// Connect to the database with the JDBC driver and create two test tables.
String projectId = instanceName.getProject();
String instanceId = instanceName.getInstance();
try (Connection connection =
DriverManager.getConnection(
String.format(
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
projectId, instanceId, databaseId),
properties)) {
try (Statement statement = connection.createStatement()) {
// Create the tables in one batch.
statement.addBatch(
"CREATE TABLE Singers ("
+ " SingerId INT64 NOT NULL,"
+ " FirstName STRING(1024),"
+ " LastName STRING(1024),"
+ " SingerInfo BYTES(MAX),"
+ " FullName STRING(2048) AS "
+ " (ARRAY_TO_STRING([FirstName, LastName], \" \")) STORED"
+ ") PRIMARY KEY (SingerId)");
statement.addBatch(
"CREATE TABLE Albums ("
+ " SingerId INT64 NOT NULL,"
+ " AlbumId INT64 NOT NULL,"
+ " AlbumTitle STRING(MAX)"
+ ") PRIMARY KEY (SingerId, AlbumId),"
+ " INTERLEAVE IN PARENT Singers ON DELETE CASCADE");
statement.executeBatch();
}
}
System.out.printf(
"Created database [%s]\n",
DatabaseName.of(projectId, instanceId, databaseId));
}
// [END spanner_create_database]
// [START spanner_postgresql_create_database]
static void createPostgreSQLDatabase(
final DatabaseAdminClient dbAdminClient,
final InstanceName instanceName,
final String databaseId,
final Properties properties) throws SQLException {
// Use the Spanner admin client to create a database.
CreateDatabaseRequest createDatabaseRequest =
CreateDatabaseRequest.newBuilder()
// PostgreSQL database names and other identifiers
// must be quoted using double quotes.
.setCreateStatement("create database \"" + databaseId + "\"")
.setParent(instanceName.toString())
.setDatabaseDialect(DatabaseDialect.POSTGRESQL)
.build();
try {
dbAdminClient.createDatabaseAsync(createDatabaseRequest).get();
} catch (ExecutionException e) {
throw SpannerExceptionFactory.asSpannerException(e.getCause());
} catch (InterruptedException e) {
throw SpannerExceptionFactory.propagateInterrupt(e);
}
// Connect to the database with the JDBC driver and create two test tables.
String projectId = instanceName.getProject();
String instanceId = instanceName.getInstance();
try (Connection connection =
DriverManager.getConnection(
String.format(
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
projectId, instanceId, databaseId),
properties)) {
try (Statement statement = connection.createStatement()) {
// Create the tables in one batch.
statement.addBatch(
"create table singers ("
+ " singer_id bigint primary key not null,"
+ " first_name varchar(1024),"
+ " last_name varchar(1024),"
+ " singer_info bytea,"
+ " full_name varchar(2048) generated always as (\n"
+ " case when first_name is null then last_name\n"
+ " when last_name is null then first_name\n"
+ " else first_name || ' ' || last_name\n"
+ " end) stored"
+ ")");
statement.addBatch(
"create table albums ("
+ " singer_id bigint not null,"
+ " album_id bigint not null,"
+ " album_title varchar,"
+ " primary key (singer_id, album_id)"
+ ") interleave in parent singers on delete cascade");
statement.executeBatch();
}
}
System.out.printf(
"Created database [%s]\n",
DatabaseName.of(projectId, instanceId, databaseId));
}
// [END spanner_postgresql_create_database]
// [START spanner_create_jdbc_connection]
static void createConnection(
final String project,
final String instance,
final String database,
final Properties properties) throws SQLException {
// Connection properties can be specified both with in a Properties object
// and in the connection URL.
properties.put("numChannels", "8");
try (Connection connection =
DriverManager.getConnection(
String.format(
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s"
+ ";minSessions=400;maxSessions=400",
project, instance, database),
properties)) {
try (ResultSet resultSet =
connection.createStatement().executeQuery("select 'Hello World!'")) {
while (resultSet.next()) {
System.out.println(resultSet.getString(1));
}
}
}
}
// [END spanner_create_jdbc_connection]
// [START spanner_create_jdbc_connection_with_emulator]
static void createConnectionWithEmulator(
final String project,
final String instance,
final String database,
final Properties properties) throws SQLException {
// Add autoConfigEmulator=true to the connection URL to instruct the JDBC
// driver to connect to the Spanner emulator on localhost:9010.
// The Spanner instance and database are automatically created if these
// don't already exist.
try (Connection connection =
DriverManager.getConnection(
String.format(
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s"
+ ";autoConfigEmulator=true",
project, instance, database),
properties)) {
try (ResultSet resultSet =
connection.createStatement().executeQuery("select 'Hello World!'")) {
while (resultSet.next()) {
System.out.println(resultSet.getString(1));
}
}
}
}
// [END spanner_create_jdbc_connection_with_emulator]
// [START spanner_dml_getting_started_insert]
static void writeDataWithDml(
final String project,
final String instance,
final String database,
final Properties properties) throws SQLException {
try (Connection connection =
DriverManager.getConnection(
String.format(
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
project, instance, database),
properties)) {
// Add 4 rows in one statement.
// JDBC always uses '?' as a parameter placeholder.
try (PreparedStatement preparedStatement =
connection.prepareStatement(
"INSERT INTO Singers (SingerId, FirstName, LastName) VALUES "
+ "(?, ?, ?), "
+ "(?, ?, ?), "
+ "(?, ?, ?), "
+ "(?, ?, ?)")) {
final ImmutableList<Singer> singers =
ImmutableList.of(
new Singer(/* SingerId = */ 12L, "Melissa", "Garcia"),
new Singer(/* SingerId = */ 13L, "Russel", "Morales"),
new Singer(/* SingerId = */ 14L, "Jacqueline", "Long"),
new Singer(/* SingerId = */ 15L, "Dylan", "Shaw"));
// Note that JDBC parameters start at index 1.
int paramIndex = 0;
for (Singer singer : singers) {
preparedStatement.setLong(++paramIndex, singer.singerId);
preparedStatement.setString(++paramIndex, singer.firstName);
preparedStatement.setString(++paramIndex, singer.lastName);
}
int updateCount = preparedStatement.executeUpdate();
System.out.printf("%d records inserted.\n", updateCount);
}
}
}
// [END spanner_dml_getting_started_insert]
// [START spanner_postgresql_dml_getting_started_insert]
static void writeDataWithDmlPostgreSQL(
final String project,
final String instance,
final String database,
final Properties properties) throws SQLException {
try (Connection connection =
DriverManager.getConnection(
String.format(
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
project, instance, database),
properties)) {
// Add 4 rows in one statement.
// JDBC always uses '?' as a parameter placeholder.
try (PreparedStatement preparedStatement =
connection.prepareStatement(
"INSERT INTO singers (singer_id, first_name, last_name) VALUES "
+ "(?, ?, ?), "
+ "(?, ?, ?), "
+ "(?, ?, ?), "
+ "(?, ?, ?)")) {
final ImmutableList<Singer> singers =
ImmutableList.of(
new Singer(/* SingerId = */ 12L, "Melissa", "Garcia"),
new Singer(/* SingerId = */ 13L, "Russel", "Morales"),
new Singer(/* SingerId = */ 14L, "Jacqueline", "Long"),
new Singer(/* SingerId = */ 15L, "Dylan", "Shaw"));
// Note that JDBC parameters start at index 1.
int paramIndex = 0;
for (Singer singer : singers) {
preparedStatement.setLong(++paramIndex, singer.singerId);
preparedStatement.setString(++paramIndex, singer.firstName);
preparedStatement.setString(++paramIndex, singer.lastName);
}
int updateCount = preparedStatement.executeUpdate();
System.out.printf("%d records inserted.\n", updateCount);
}
}
}
// [END spanner_postgresql_dml_getting_started_insert]
// [START spanner_dml_batch]
static void writeDataWithDmlBatch(
final String project,
final String instance,
final String database,
final Properties properties) throws SQLException {
try (Connection connection =
DriverManager.getConnection(
String.format(
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
project, instance, database),
properties)) {
// Add multiple rows in one DML batch.
// JDBC always uses '?' as a parameter placeholder.
try (PreparedStatement preparedStatement =
connection.prepareStatement(
"INSERT INTO Singers (SingerId, FirstName, LastName) "
+ "VALUES (?, ?, ?)")) {
final ImmutableList<Singer> singers =
ImmutableList.of(
new Singer(/* SingerId = */ 16L, "Sarah", "Wilson"),
new Singer(/* SingerId = */ 17L, "Ethan", "Miller"),
new Singer(/* SingerId = */ 18L, "Maya", "Patel"));
for (Singer singer : singers) {
// Note that JDBC parameters start at index 1.
int paramIndex = 0;
preparedStatement.setLong(++paramIndex, singer.singerId);
preparedStatement.setString(++paramIndex, singer.firstName);
preparedStatement.setString(++paramIndex, singer.lastName);
preparedStatement.addBatch();
}
int[] updateCounts = preparedStatement.executeBatch();
System.out.printf(
"%d records inserted.\n",
Arrays.stream(updateCounts).sum());
}
}
}
// [END spanner_dml_batch]
// [START spanner_postgresql_dml_batch]
static void writeDataWithDmlBatchPostgreSQL(
final String project,
final String instance,
final String database,
final Properties properties) throws SQLException {
try (Connection connection =
DriverManager.getConnection(
String.format(
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
project, instance, database),
properties)) {
// Add multiple rows in one DML batch.
// JDBC always uses '?' as a parameter placeholder.
try (PreparedStatement preparedStatement =
connection.prepareStatement(
"INSERT INTO singers (singer_id, first_name, last_name)"
+ " VALUES (?, ?, ?)")) {
final ImmutableList<Singer> singers =
ImmutableList.of(
new Singer(/* SingerId = */ 16L, "Sarah", "Wilson"),
new Singer(/* SingerId = */ 17L, "Ethan", "Miller"),
new Singer(/* SingerId = */ 18L, "Maya", "Patel"));
for (Singer singer : singers) {
// Note that JDBC parameters start at index 1.
int paramIndex = 0;
preparedStatement.setLong(++paramIndex, singer.singerId);
preparedStatement.setString(++paramIndex, singer.firstName);
preparedStatement.setString(++paramIndex, singer.lastName);
preparedStatement.addBatch();
}
int[] updateCounts = preparedStatement.executeBatch();
System.out.printf(
"%d records inserted.\n",
Arrays.stream(updateCounts).sum());
}
}
}
// [END spanner_postgresql_dml_batch]
// [START spanner_insert_data]
static void writeDataWithMutations(
final String project,
final String instance,
final String database,
final Properties properties) throws SQLException {
try (Connection connection =
DriverManager.getConnection(
String.format(
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
project, instance, database),
properties)) {
// Unwrap the CloudSpannerJdbcConnection interface
// from the java.sql.Connection.
CloudSpannerJdbcConnection cloudSpannerJdbcConnection =
connection.unwrap(CloudSpannerJdbcConnection.class);
List<Mutation> mutations = new ArrayList<>();
for (Singer singer : SINGERS) {
mutations.add(
Mutation.newInsertBuilder("Singers")
.set("SingerId")
.to(singer.singerId)
.set("FirstName")
.to(singer.firstName)
.set("LastName")
.to(singer.lastName)
.build());
}
for (Album album : ALBUMS) {
mutations.add(
Mutation.newInsertBuilder("Albums")
.set("SingerId")
.to(album.singerId)
.set("AlbumId")
.to(album.albumId)
.set("AlbumTitle")
.to(album.albumTitle)
.build());
}
// Apply the mutations atomically to Spanner.
cloudSpannerJdbcConnection.write(mutations);
System.out.printf("Inserted %d rows.\n", mutations.size());
}
}
// [END spanner_insert_data]
// [START spanner_postgresql_insert_data]
static void writeDataWithMutationsPostgreSQL(
final String project,
final String instance,
final String database,
final Properties properties) throws SQLException {
try (Connection connection =
DriverManager.getConnection(
String.format(
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
project, instance, database),
properties)) {
// Unwrap the CloudSpannerJdbcConnection interface
// from the java.sql.Connection.
CloudSpannerJdbcConnection cloudSpannerJdbcConnection =
connection.unwrap(CloudSpannerJdbcConnection.class);
List<Mutation> mutations = new ArrayList<>();
for (Singer singer : SINGERS) {
mutations.add(
Mutation.newInsertBuilder("singers")
.set("singer_id")
.to(singer.singerId)
.set("first_name")
.to(singer.firstName)
.set("last_name")
.to(singer.lastName)
.build());
}
for (Album album : ALBUMS) {
mutations.add(
Mutation.newInsertBuilder("albums")
.set("singer_id")
.to(album.singerId)
.set("album_id")
.to(album.albumId)
.set("album_title")
.to(album.albumTitle)
.build());
}
// Apply the mutations atomically to Spanner.
cloudSpannerJdbcConnection.write(mutations);
System.out.printf("Inserted %d rows.\n", mutations.size());
}
}
// [END spanner_postgresql_insert_data]
// [START spanner_query_data]
static void queryData(
final String project,
final String instance,
final String database,
final Properties properties) throws SQLException {
try (Connection connection =
DriverManager.getConnection(
String.format(
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
project, instance, database),
properties)) {
try (ResultSet resultSet =
connection
.createStatement()
.executeQuery(
"SELECT SingerId, AlbumId, AlbumTitle "
+ "FROM Albums")) {
while (resultSet.next()) {
System.out.printf(
"%d %d %s\n",
resultSet.getLong("SingerId"),
resultSet.getLong("AlbumId"),
resultSet.getString("AlbumTitle"));
}
}
}
}
// [END spanner_query_data]
// [START spanner_postgresql_query_data]
static void queryDataPostgreSQL(
final String project,
final String instance,
final String database,
final Properties properties) throws SQLException {
try (Connection connection =
DriverManager.getConnection(
String.format(
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
project, instance, database),
properties)) {
try (ResultSet resultSet =
connection
.createStatement()
.executeQuery(
"SELECT singer_id, album_id, album_title "
+ "FROM albums")) {
while (resultSet.next()) {
System.out.printf(
"%d %d %s\n",
resultSet.getLong("singer_id"),
resultSet.getLong("album_id"),
resultSet.getString("album_title"));
}
}
}
}
// [END spanner_postgresql_query_data]
// [START spanner_query_with_parameter]
static void queryWithParameter(
final String project,
final String instance,
final String database,
final Properties properties) throws SQLException {
try (Connection connection =
DriverManager.getConnection(
String.format(
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
project, instance, database),
properties)) {
try (PreparedStatement statement =
connection.prepareStatement(
"SELECT SingerId, FirstName, LastName "
+ "FROM Singers "
+ "WHERE LastName = ?")) {
statement.setString(1, "Garcia");
try (ResultSet resultSet = statement.executeQuery()) {
while (resultSet.next()) {
System.out.printf(
"%d %s %s\n",
resultSet.getLong("SingerId"),
resultSet.getString("FirstName"),
resultSet.getString("LastName"));
}
}
}
}
}
// [END spanner_query_with_parameter]
// [START spanner_postgresql_query_with_parameter]
static void queryWithParameterPostgreSQL(
final String project,
final String instance,
final String database,
final Properties properties) throws SQLException {
try (Connection connection =
DriverManager.getConnection(
String.format(
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
project, instance, database),
properties)) {
try (PreparedStatement statement =
connection.prepareStatement(
"SELECT singer_id, first_name, last_name "
+ "FROM singers "
+ "WHERE last_name = ?")) {
statement.setString(1, "Garcia");
try (ResultSet resultSet = statement.executeQuery()) {
while (resultSet.next()) {
System.out.printf(
"%d %s %s\n",
resultSet.getLong("singer_id"),
resultSet.getString("first_name"),
resultSet.getString("last_name"));
}
}
}
}
}
// [END spanner_postgresql_query_with_parameter]
// [START spanner_add_column]
static void addColumn(
final String project,
final String instance,
final String database,
final Properties properties) throws SQLException {
try (Connection connection =
DriverManager.getConnection(
String.format(
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
project, instance, database),
properties)) {
connection
.createStatement()
.execute("ALTER TABLE Albums ADD COLUMN MarketingBudget INT64");
System.out.println("Added MarketingBudget column");
}
}
// [END spanner_add_column]
// [START spanner_postgresql_add_column]
static void addColumnPostgreSQL(
final String project,
final String instance,
final String database,
final Properties properties) throws SQLException {
try (Connection connection =
DriverManager.getConnection(
String.format(
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
project, instance, database),
properties)) {
connection
.createStatement()
.execute("alter table albums add column marketing_budget bigint");
System.out.println("Added marketing_budget column");
}
}
// [END spanner_postgresql_add_column]
// [START spanner_ddl_batch]
static void ddlBatch(
final String project,
final String instance,
final String database,
final Properties properties) throws SQLException {
try (Connection connection =
DriverManager.getConnection(
String.format(
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
project, instance, database),
properties)) {
try (Statement statement = connection.createStatement()) {
// Create two new tables in one batch.
statement.addBatch(
"CREATE TABLE Venues ("
+ " VenueId INT64 NOT NULL,"
+ " Name STRING(1024),"
+ " Description JSON"
+ ") PRIMARY KEY (VenueId)");
statement.addBatch(
"CREATE TABLE Concerts ("
+ " ConcertId INT64 NOT NULL,"
+ " VenueId INT64 NOT NULL,"
+ " SingerId INT64 NOT NULL,"
+ " StartTime TIMESTAMP,"
+ " EndTime TIMESTAMP,"
+ " CONSTRAINT Fk_Concerts_Venues FOREIGN KEY"
+ " (VenueId) REFERENCES Venues (VenueId),"
+ " CONSTRAINT Fk_Concerts_Singers FOREIGN KEY"
+ " (SingerId) REFERENCES Singers (SingerId),"
+ ") PRIMARY KEY (ConcertId)");
statement.executeBatch();
}
System.out.println("Added Venues and Concerts tables");
}
}
// [END spanner_ddl_batch]
// [START spanner_postgresql_ddl_batch]
static void ddlBatchPostgreSQL(
final String project,
final String instance,
final String database,
final Properties properties) throws SQLException {
try (Connection connection =
DriverManager.getConnection(
String.format(
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
project, instance, database),
properties)) {
try (Statement statement = connection.createStatement()) {
// Create two new tables in one batch.
statement.addBatch(
"CREATE TABLE venues ("
+ " venue_id bigint not null primary key,"
+ " name varchar(1024),"
+ " description jsonb"
+ ")");
statement.addBatch(
"CREATE TABLE concerts ("
+ " concert_id bigint not null primary key ,"
+ " venue_id bigint not null,"
+ " singer_id bigint not null,"
+ " start_time timestamptz,"
+ " end_time timestamptz,"
+ " constraint fk_concerts_venues foreign key"
+ " (venue_id) references venues (venue_id),"
+ " constraint fk_concerts_singers foreign key"
+ " (singer_id) references singers (singer_id)"
+ ")");
statement.executeBatch();
}
System.out.println("Added venues and concerts tables");
}
}
// [END spanner_postgresql_ddl_batch]
// [START spanner_update_data]
static void updateDataWithMutations(
final String project,
final String instance,
final String database,
final Properties properties) throws SQLException {
try (Connection connection =
DriverManager.getConnection(
String.format(
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
project, instance, database),
properties)) {
// Unwrap the CloudSpannerJdbcConnection interface
// from the java.sql.Connection.
CloudSpannerJdbcConnection cloudSpannerJdbcConnection =
connection.unwrap(CloudSpannerJdbcConnection.class);
final long marketingBudgetAlbum1 = 100000L;
final long marketingBudgetAlbum2 = 500000L;
// Mutation can be used to update/insert/delete a single row in a table.
// Here we use newUpdateBuilder to create update mutations.
List<Mutation> mutations =
Arrays.asList(
Mutation.newUpdateBuilder("Albums")
.set("SingerId")
.to(1)
.set("AlbumId")
.to(1)
.set("MarketingBudget")
.to(marketingBudgetAlbum1)
.build(),
Mutation.newUpdateBuilder("Albums")
.set("SingerId")
.to(2)
.set("AlbumId")
.to(2)
.set("MarketingBudget")
.to(marketingBudgetAlbum2)
.build());
// This writes all the mutations to Cloud Spanner atomically.
cloudSpannerJdbcConnection.write(mutations);
System.out.println("Updated albums");
}
}
// [END spanner_update_data]
// [START spanner_postgresql_update_data]
static void updateDataWithMutationsPostgreSQL(
final String project,
final String instance,
final String database,
final Properties properties) throws SQLException {
try (Connection connection =
DriverManager.getConnection(
String.format(
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
project, instance, database),
properties)) {
// Unwrap the CloudSpannerJdbcConnection interface
// from the java.sql.Connection.
CloudSpannerJdbcConnection cloudSpannerJdbcConnection =
connection.unwrap(CloudSpannerJdbcConnection.class);
final long marketingBudgetAlbum1 = 100000L;
final long marketingBudgetAlbum2 = 500000L;
// Mutation can be used to update/insert/delete a single row in a table.
// Here we use newUpdateBuilder to create update mutations.
List<Mutation> mutations =
Arrays.asList(
Mutation.newUpdateBuilder("albums")
.set("singer_id")
.to(1)
.set("album_id")
.to(1)
.set("marketing_budget")
.to(marketingBudgetAlbum1)
.build(),
Mutation.newUpdateBuilder("albums")
.set("singer_id")
.to(2)
.set("album_id")
.to(2)
.set("marketing_budget")
.to(marketingBudgetAlbum2)
.build());
// This writes all the mutations to Cloud Spanner atomically.
cloudSpannerJdbcConnection.write(mutations);
System.out.println("Updated albums");
}
}
// [END spanner_postgresql_update_data]
// [START spanner_query_data_with_new_column]
static void queryDataWithNewColumn(
final String project,
final String instance,
final String database,
final Properties properties) throws SQLException {
try (Connection connection =
DriverManager.getConnection(
String.format(
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
project, instance, database),
properties)) {
// Rows without an explicit value for MarketingBudget will have a
// MarketingBudget equal to null.
try (ResultSet resultSet =
connection
.createStatement()
.executeQuery(
"SELECT SingerId, AlbumId, MarketingBudget "
+ "FROM Albums")) {
while (resultSet.next()) {
// Use the ResultSet#getObject(String) method to get data
// of any type from the ResultSet.
System.out.printf(
"%s %s %s\n",
resultSet.getObject("SingerId"),
resultSet.getObject("AlbumId"),
resultSet.getObject("MarketingBudget"));
}
}
}
}
// [END spanner_query_data_with_new_column]
// [START spanner_postgresql_query_data_with_new_column]
static void queryDataWithNewColumnPostgreSQL(
final String project,
final String instance,
final String database,
final Properties properties) throws SQLException {
try (Connection connection =
DriverManager.getConnection(
String.format(
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
project, instance, database),
properties)) {
// Rows without an explicit value for marketing_budget will have a
// marketing_budget equal to null.
try (ResultSet resultSet =
connection
.createStatement()
.executeQuery(
"select singer_id, album_id, marketing_budget "
+ "from albums")) {
while (resultSet.next()) {
// Use the ResultSet#getObject(String) method to get data
// of any type from the ResultSet.
System.out.printf(
"%s %s %s\n",
resultSet.getObject("singer_id"),
resultSet.getObject("album_id"),
resultSet.getObject("marketing_budget"));
}
}
}
}
// [END spanner_postgresql_query_data_with_new_column]
// [START spanner_dml_getting_started_update]
static void writeWithTransactionUsingDml(
final String project,
final String instance,
final String database,
final Properties properties) throws SQLException {
try (Connection connection =
DriverManager.getConnection(
String.format(
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
project, instance, database),
properties)) {
// Set AutoCommit=false to enable transactions.
connection.setAutoCommit(false);
// Transfer marketing budget from one album to another.
// We do it in a transaction to ensure that the transfer is atomic.
// There is no need to explicitly start the transaction. The first
// statement on the connection will start a transaction when
// AutoCommit=false.
String selectMarketingBudgetSql =
"SELECT MarketingBudget "
+ "FROM Albums "
+ "WHERE SingerId = ? AND AlbumId = ?";
long album2Budget = 0;
try (PreparedStatement selectMarketingBudgetStatement =
connection.prepareStatement(selectMarketingBudgetSql)) {
// Bind the query parameters to SingerId=2 and AlbumId=2.