aboutsummaryrefslogtreecommitdiff
path: root/doc/src/sgml/jdbc.sgml
blob: fb00aa829ea6333c46c7316de5f6257a3f030aa5 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
<!--
$Header: /cvsroot/pgsql/doc/src/sgml/Attic/jdbc.sgml,v 1.15 2000/10/27 22:28:23 momjian Exp $
-->

 <chapter id="jdbc">
  <title>JDBC Interface</title>

  <para>
   <note>
    <title>Author</title>
    <para>
     Written by <ulink url="mailto:peter@retep.org.uk">Peter T. Mount</ulink>, the
     author of the <acronym>JDBC</acronym> driver.
    </para>
   </note>
  </para>

  <para>
   <acronym>JDBC</acronym> is a core <acronym>API</acronym> of Java 1.1 and later.
   It provides a standard set of
   interfaces to <acronym>SQL</acronym>-compliant databases.
  </para>

  <para>
   <application>Postgres</application> provides 
   a <firstterm>type 4</firstterm> <acronym>JDBC</acronym> Driver.
   Type 4 indicates that the driver
   is written in Pure Java, and communicates in the database's own network
   protocol. Because of this, the driver is platform independent. Once compiled,
   the driver can be used on any platform.
  </para>

  <sect1 id="jdbc-build">
   <title>Building the <acronym>JDBC</acronym> Interface</title>

   <sect2>
    <title>Compiling the Driver</title>

    <para>
     The driver's source is located in the <filename>src/interfaces/jdbc</filename>
     directory of the
     source tree. To compile simply change directory to that directory, and type:

     <programlisting>
% make
     </programlisting>
    </para>

    <para>
     Upon completion, you will find the archive <filename>postgresql.jar</filename>
     in the current
     directory. This is the <acronym>JDBC</acronym> driver.

     <note>
      <para>
       You must use <application>make</application>,
       not <application>javac</application>, 
       as the driver uses some dynamic
       loading techniques for performance reasons, 
       and <application>javac</application> cannot cope.
       The <filename>Makefile</filename> will generate the jar archive.
      </para>
     </note>
    </para>
   </sect2>

   <sect2>
    <title>Installing the Driver</title>

    <para>
     To use the driver, the jar archive postgresql.jar needs to be included in
     the <envar>CLASSPATH</envar>.
    </para>

    <sect3>
     <title>Example</title>

     <para>
      I have an application that uses the <acronym>JDBC</acronym> driver to access a large database
      containing astronomical objects. I have the application and the jdbc driver
      installed in the /usr/local/lib directory, and the java jdk installed in /usr/local/jdk1.1.6.
     </para>

     <para>
      To run the application, I would use:

      <programlisting>
export CLASSPATH = /usr/local/lib/finder.jar:/usr/local/lib/postgresql.jar:.
java uk.org.retep.finder.Main
      </programlisting>
     </para>

     <para>
      Loading the driver is covered later on in this chapter.
     </para>
    </sect3>
   </sect2>
  </sect1>

  <sect1 id="jdbc-prepare">
   <title>Preparing the Database for <acronym>JDBC</acronym></title>

   <para>
    Because Java can only use TCP/IP connections, the <application>Postgres</application> postmaster
    must be running with the -i flag.
   </para>

   <para>
    Also, the <filename>pg_hba.conf</filename> file must be configured. It's located in the PGDATA
    directory. In a default installation, this file permits access only by Unix
    domain sockets. For the <acronym>JDBC</acronym> driver to connect to the same localhost, you need
    to add something like:

    <programlisting>
host         all         127.0.0.1     255.255.255.255   password
    </programlisting>

    Here access to all databases are possible from the local machine 
    with <acronym>JDBC</acronym>.
   </para>

   <para>
    The <acronym>JDBC</acronym> Driver supports trust, ident, 
    password and crypt authentication methods.
   </para>
  </sect1>

  <sect1 id="jdbc-use">
   <title>Using the Driver</title>

   <para>
    This section is not intended as a complete guide to 
    <acronym>JDBC</acronym> programming, but
    should help to get you started. For more information refer to the standard
    <acronym>JDBC</acronym> <acronym>API</acronym> documentation.
    Also, take a look at the examples included with the source. The basic
    example is used here.
   </para>
  </sect1>

  <sect1 id="jdbc-import">
   <title>Importing <acronym>JDBC</acronym></title>

   <para>
    Any source that uses <acronym>JDBC</acronym>
    needs to import the java.sql package, using:

    <programlisting>
import java.sql.*;
    </programlisting>

    <important>
     <para>
      Do not import the postgresql package. If you do, your source will not
      compile, as javac will get confused.
     </para>
    </important>
   </para>
  </sect1>

  <sect1 id="jdbc-load">
   <title>Loading the Driver</title>

   <para>
    Before you can connect to a database, you need to load the driver. There
    are two methods available, and it depends on your code to the best one to use.
   </para>

   <para>
    In the first method, your code implicitly loads the driver using the
    <function>Class.forName()</function> method.
    For <application>Postgres</application>, you would use:

    <programlisting>
Class.forName("org.postgresql.Driver");
    </programlisting>

    This will load the driver, and while loading, the driver will automatically
    register itself with <acronym>JDBC</acronym>.
   </para>

   <para>
    Note: The <function>forName()</function> method
    can throw a <literal>ClassNotFoundException</literal>, so you will
    need to catch it if the driver is not available.
   </para>

   <para>
    This is the most common method to use, but restricts your code to use just
    <application>Postgres</application>. 
    If your code may access another database in the future, and you
    don't use our extensions, then the second method is advisable.
   </para>

   <para>
    The second method passes the driver as a parameter to the JVM as it starts,
    using the -D argument. Example:

    <programlisting>
% java -Djdbc.drivers=org.postgresql.Driver example.ImageViewer
    </programlisting>

    In this example, the JVM will attempt to load the driver as part of it's
    initialisation. Once done, the ImageViewer is started.
   </para>

   <para>
    Now, this method is the better one to use because it allows your code to
    be used with other databases, without recompiling the code. The only thing
    that would also change is the URL, which is covered next.
   </para>

   <para>
    One last thing. When your code then tries to open a Connection, and you get
    a <literal>No driver available</literal> SQLException being thrown,
    this is probably
    caused by the driver not being in the classpath, or the value in the parameter
    not being correct.
   </para>
  </sect1>

  <sect1 id="jdbc-connect">
   <title>Connecting to the Database</title>

   <para>
    With <acronym>JDBC</acronym>, a database is represented by a URL 
    (Uniform Resource Locator).
    With <application>Postgres</application>, this takes one of the following
    forms:

    <itemizedlist>
     <listitem>
      <para>
       jdbc:postgresql:<replaceable class="parameter">database</replaceable>
      </para>
     </listitem>

     <listitem>
      <para>
       jdbc:postgresql://<replaceable class="parameter">host</replaceable>/<replaceable class="parameter">database</replaceable>
      </para>
     </listitem>

     <listitem>
      <para>
       jdbc:postgresql://<replaceable class="parameter">host</replaceable><replaceable class="parameter">port</replaceable>/<replaceable class="parameter">database</replaceable>
      </para>
     </listitem>
    </itemizedlist>

    where:

    <variablelist>
     <varlistentry>
      <term>
       <replaceable class="parameter">host</replaceable>
      </term>
      <listitem>
       <para>
	The hostname of the server. Defaults to "localhost".
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term>
       <replaceable class="parameter">port</replaceable>
      </term>
      <listitem>
       <para>
	The port number the server is listening on. Defaults to the Postgres
	standard port number (5432).
       </para>
      </listitem>
     </varlistentry>

     <varlistentry>
      <term>
       <replaceable class="parameter">database</replaceable>
      </term>
      <listitem>
       <para>
	The database name.
       </para>
      </listitem>
     </varlistentry>
    </variablelist>
   </para>

   <para>
    To connect, you need to get a Connection instance from 
    <acronym>JDBC</acronym>. To do this,
    you would use the DriverManager.getConnection() method:

    <programlisting>
Connection db = DriverManager.getConnection(url,user,pwd);
    </programlisting>
   </para>
  </sect1>

  <sect1 id="jdbc-query">
   <title>Issuing a Query and Processing the Result</title>

   <para>
    Any time you want to issue SQL statements to the database, you require a
    Statement instance. Once you have a Statement, you can use the executeQuery()
    method to issue a query. This will return a ResultSet instance, which contains
    the entire result.
   </para>

   <sect2>
    <title>Using the Statement Interface</title>

    <para>
     The following must be considered when using the Statement interface:

     <itemizedlist>
      <listitem>
       <para>
	You can use a Statement instance as many times as you want. You could
	create one as soon as you open the connection, and use it for the connections
	lifetime. You have to remember that only one ResultSet can exist per Statement.
       </para>
      </listitem>

      <listitem>
       <para>
	If you need to perform a query while processing a ResultSet, you can
	simply create and use another Statement.
       </para>
      </listitem>
      <listitem>
       <para>
	If you are using Threads, and several are using the database, you must
	use a separate Statement for each thread. Refer to the sections covering
	Threads and Servlets later in this document if you are thinking of using them,
	as it covers some important points.
       </para>
      </listitem>
     </itemizedlist>
    </para>
   </sect2>

   <sect2>
    <title>Using the ResultSet Interface</title>

    <para>
     The following must be considered when using the ResultSet interface:

     <itemizedlist>
      <listitem>
       <para>
	Before reading any values, you must call <function>next()</function>. This returns true if
	there is a result, but more importantly, it prepares the row for processing.
       </para>
      </listitem>

      <listitem>
       <para>
	Under the <acronym>JDBC</acronym> spec, you should access a
	field only once. It's safest to stick to this rule, although
	at the current time, the <application>Postgres</application> driver
	will allow you to access a field as many times as you want.
       </para>
      </listitem>

      <listitem>
       <para>
	You must close a ResultSet by calling
	<function>close()</function> once you have finished with it.
       </para>
      </listitem>

      <listitem>
       <para>
	Once you request another query with the Statement used to create a
	ResultSet, the currently open instance is closed.
       </para>
      </listitem>
     </itemizedlist>
    </para>

    <para>
     An example is as follows:

     <programlisting>
Statement st = db.createStatement();
ResultSet rs = st.executeQuery("select * from mytable");
while(rs.next()) {
    System.out.print("Column 1 returned ");
    System.out.println(rs.getString(1));
}
rs.close();
st.close();
     </programlisting>
    </para>
   </sect2>
  </sect1>

  <sect1 id="jdbc-update">
   <title>Performing Updates</title>

   <para>
    To perform an update (or any other SQL statement that does not return a
    result), you simply use the <function>executeUpdate()</function> method:

    <programlisting>
st.executeUpdate("create table basic (a int2, b int2)");
    </programlisting>
   </para>
  </sect1>

  <sect1 id="jdbc-disconnect">
   <title>Closing the Connection</title>

   <para>
    To close the database connection, simply call the close() method to the Connection:

    <programlisting>
db.close();
    </programlisting>
   </para>
  </sect1>

  <sect1 id="jdbc-lo">
   <title>Using Large Objects</title>

   <para>
    In <application>Postgres</application>, 
    large objects (also known as <firstterm>blobs</firstterm>) are used to hold data in
    the database that cannot be stored in a normal SQL table. They are stored as a
    Table/Index pair, and are referred to from your own tables by an OID value.
   </para>

   <para>
    <important>
     <para>
      For <productname>Postgres</productname>, you must access large
      objects within an SQL transaction. Although this has always been 
      true in principle, it was not strictly enforced until the
      release of v6.5. You would open a transaction by using the
      <function>setAutoCommit()</function> method with an input
      parameter of <literal>false</literal>:

      <programlisting>
Connection mycon;
...
mycon.setAutoCommit(false);
... now use Large Objects
      </programlisting>
     </para>
    </important>
   </para>

   <para>
    Now, there are two methods of using Large Objects. The first is the
    standard <acronym>JDBC</acronym> way, and is documented here. The
    other, uses our own extension
    to the api, which presents the libpq large object
    <acronym>API</acronym> to Java, providing even
    better access to large objects than the standard. Internally, the driver uses
    the extension to provide large object support.
   </para>

   <para>
    In <acronym>JDBC</acronym>, the standard way to access them is using the getBinaryStream()
    method in ResultSet, and setBinaryStream() method in PreparedStatement. These
    methods make the large object appear as a Java stream, allowing you to use the
    java.io package, and others, to manipulate the object.
   </para>

   <para>
    For example, suppose
    you have a table containing the file name of an image, and a large object
    containing that image:

    <programlisting>
create table images (imgname name,imgoid oid);
    </programlisting>
   </para>

   <para>
    To insert an image, you would use:

    <programlisting>
File file = new File("myimage.gif");
FileInputStream fis = new FileInputStream(file);
PreparedStatement ps = conn.prepareStatement("insert into images values (?,?)");
ps.setString(1,file.getName());
ps.setBinaryStream(2,fis,file.length());
ps.executeUpdate();
ps.close();
fis.close();
    </programlisting>
   </para>

   <para>
    Now in this example, setBinaryStream transfers a set number of bytes from a
    stream into a large object, and stores the OID into the field holding a
    reference to it.
   </para>

   <para>
    Retrieving an image is even easier (I'm using PreparedStatement here, but
    Statement can equally be used):

    <programlisting>
PreparedStatement ps = con.prepareStatement("select oid from images where name=?");
ps.setString(1,"myimage.gif");
ResultSet rs = ps.executeQuery();
if(rs!=null) {
    while(rs.next()) {
        InputStream is = rs.getBinaryInputStream(1);
        // use the stream in some way here
        is.close();
    }
    rs.close();
}
ps.close();
    </programlisting>
   </para>

   <para>
    Now here you can see where the Large Object is retrieved as an InputStream.
    You'll also notice that we close the stream before processing the next row in
    the result. This is part of the <acronym>JDBC</acronym> Specification, which states that any
    InputStream returned is closed when ResultSet.next() or ResultSet.close() is called.
   </para>
  </sect1>

  <sect1 id="jdbc-ext">
   <title><application>Postgres</application> Extensions to the
    <acronym>JDBC</acronym> <acronym>API</acronym></title>

   <para>
    <application>Postgres</application> is an extensible database system. 
    You can add your own functions
    to the backend, which can then be called from queries, or even add your own
    data types.
   </para>

   <para>
    Now, as these are facilities unique to us, we support them from Java, with
    a set of extension <acronym>API</acronym>'s. Some features within 
    the core of the standard driver
    actually use these extensions to implement Large Objects, etc.

<!--
************************************************************
Nothing marked up from here on. It looks like it will be tricky:
what do we want to do with the class inheritance diagrams?
- thomas 1998-10-23
************************************************************
-->

<programlisting>
Accessing the extensions

To access some of the extensions, you need to use some extra methods 
in the postgresql.Connection class. In this case, you would need to 
case the return value of Driver.getConnection().

For example:

    Connection db = Driver.getConnection(url,user,pass);

    // later on
    Fastpath fp = ((postgresql.Connection)db).getFastpathAPI();

Class postgresql.Connection
                                
java.lang.Object
   |
   +----postgresql.Connection

   public class Connection extends Object implements Connection

These are the extra methods used to gain access to our extensions. I 
have not listed the methods defined by java.sql.Connection.

 public Fastpath getFastpathAPI() throws SQLException

          This returns the Fastpath <acronym>API</acronym> for the current connection.

          NOTE: This is not part of <acronym>JDBC</acronym>, but allows access to 
functions on the postgresql backend itself.

          It is primarily used by the LargeObject <acronym>API</acronym>

          The best way to use this is as follows:

 import postgresql.fastpath.*;
 ...
 Fastpath fp = ((postgresql.Connection)myconn).getFastpathAPI();

          where myconn is an open Connection to postgresql.

        Returns:
                Fastpath object allowing access to functions on the 
postgresql backend.

        Throws: SQLException
                by Fastpath when initialising for first time
          
 public LargeObjectManager getLargeObjectAPI() throws SQLException

          This returns the LargeObject <acronym>API</acronym> for the current connection.

          NOTE: This is not part of <acronym>JDBC</acronym>, but allows access to 
functions on the postgresql backend itself.
   
          The best way to use this is as follows:

 import postgresql.largeobject.*;
 ...
 LargeObjectManager lo = 
((postgresql.Connection)myconn).getLargeObjectAPI();

          where myconn is an open Connection to postgresql.

        Returns:
                LargeObject object that implements the <acronym>API</acronym>

        Throws: SQLException
                by LargeObject when initialising for first time

 public void addDataType(String type,
                         String name)

          This allows client code to add a handler for one of 
postgresql's more unique data types. Normally, a data type not known 
by the driver is returned by ResultSet.getObject() as a PGobject 
instance.

This method allows you to write a class that extends PGobject, and 
tell the driver the type name, and class name to use.

The down side to this, is that you must call this method each time a 
connection is made.

          NOTE: This is not part of <acronym>JDBC</acronym>, but an extension.

          The best way to use this is as follows:

 ...
 ((postgresql.Connection)myconn).addDataType("mytype","my.class.name"-
);
 ...

          where myconn is an open Connection to postgresql.

          The handling class must extend postgresql.util.PGobject

        See Also:
                PGobject

Fastpath

Fastpath is an <acronym>API</acronym> that exists within the libpq C interface, and 
allows a client machine to execute a function on the database backend. 
Most client code will not need to use this method, but it's provided 
because the Large Object <acronym>API</acronym> uses it.

To use, you need to import the postgresql.fastpath package, using the 
line:
     import postgresql.fastpath.*;

Then, in your code, you need to get a FastPath object:
     Fastpath fp = ((postgresql.Connection)conn).getFastpathAPI();

This will return an instance associated with the database connection 
that you can use to issue commands. The casing of Connection to 
postgresql.Connection is required, as the getFastpathAPI() is one of 
our own methods, not <acronym>JDBC</acronym>'s.

Once you have a Fastpath instance, you can use the fastpath() methods 
to execute a backend function.

Class postgresql.fastpath.Fastpath

java.lang.Object
   |
   +----postgresql.fastpath.Fastpath

   public class Fastpath

   extends Object

   This class implements the Fastpath api.

   This is a means of executing functions imbeded in the postgresql 
backend from within a java application.

   It is based around the file src/interfaces/libpq/fe-exec.c

   See Also:
          FastpathFastpathArg, LargeObject

Methods

 public Object fastpath(int fnid,
                        boolean resulttype,
                        FastpathArg args[]) throws SQLException

          Send a function call to the PostgreSQL backend
          
        Parameters:
                fnid - Function id
                resulttype - True if the result is an integer, false 
for
                other results
                args - FastpathArguments to pass to fastpath

        Returns:
                null if no data, Integer if an integer result, or 
byte[]
                otherwise
         
        Throws: SQLException
                if a database-access error occurs.

 public Object fastpath(String name,
                        boolean resulttype,
                        FastpathArg args[]) throws SQLException

          Send a function call to the PostgreSQL backend by name. 

Note:
          the mapping for the procedure name to function id needs to 
exist, usually to an earlier call to addfunction(). This is the 
prefered method to call, as function id's can/may change between 
versions of the backend. For an example of how this works, refer to 
postgresql.LargeObject

        Parameters:
                name - Function name
                resulttype - True if the result is an integer, false 
for
                other results
                args - FastpathArguments to pass to fastpath

        Returns:
                null if no data, Integer if an integer result, or 
byte[]
                otherwise

        Throws: SQLException
                if name is unknown or if a database-access error 
occurs.

        See Also:
                LargeObject
          
 public int getInteger(String name,
                       FastpathArg args[]) throws SQLException

          This convenience method assumes that the return value is an 
Integer

        Parameters:
                name - Function name
                args - Function arguments

        Returns:
                integer result

        Throws: SQLException
                if a database-access error occurs or no result

 public byte[] getData(String name,
                       FastpathArg args[]) throws SQLException

          This convenience method assumes that the return value is 
binary data

        Parameters:
                name - Function name
                args - Function arguments

        Returns:
                byte[] array containing result

        Throws: SQLException
                if a database-access error occurs or no result

 public void addFunction(String name,
                         int fnid)

          This adds a function to our lookup table.

          User code should use the addFunctions method, which is based 
upon a query, rather than hard coding the oid. The oid for a function 
is not guaranteed to remain static, even on different servers of the 
same version.

        Parameters:
                name - Function name
                fnid - Function id

 public void addFunctions(ResultSet rs) throws SQLException
                       
          This takes a ResultSet containing two columns. Column 1 
contains the function name, Column 2 the oid.

          It reads the entire ResultSet, loading the values into the 
function table.

          REMEMBER to close() the resultset after calling this!!

          Implementation note about function name lookups:
          
          PostgreSQL stores the function id's and their corresponding 
names in the pg_proc table. To speed things up locally, instead of 
querying each function from that table when required, a Hashtable is 
used. Also, only the function's required are entered into this table, 
keeping connection times as fast as possible.

          The postgresql.LargeObject class performs a query upon it's 
start-up, and passes the returned ResultSet to the addFunctions() 
method here.
       
          Once this has been done, the LargeObject api refers to the 
functions by name.
          
          Dont think that manually converting them to the oid's will 
work. Ok, they will for now, but they can change during development 
(there was some discussion about this for V7.0), so this is 
implemented to prevent any unwarranted headaches in the future.

        Parameters:
                rs - ResultSet

        Throws: SQLException
                if a database-access error occurs.
          
        See Also:
                LargeObjectManager

 public int getID(String name) throws SQLException
          
          This returns the function id associated by its name
          
          If addFunction() or addFunctions() have not been called for 
this name, then an SQLException is thrown.

        Parameters:
                name - Function name to lookup

        Returns:
                Function ID for fastpath call

        Throws: SQLException
                is function is unknown.

Class postgresql.fastpath.FastpathArg

java.lang.Object
   |
   +----postgresql.fastpath.FastpathArg

   public class FastpathArg extends Object
        
   Each fastpath call requires an array of arguments, the number and 
type dependent on the function being called.

   This class implements methods needed to provide this capability.

   For an example on how to use this, refer to the 
postgresql.largeobject package

   See Also:
          Fastpath, LargeObjectManager, LargeObject

Constructors

 public FastpathArg(int value)
 
          Constructs an argument that consists of an integer value

        Parameters:
                value - int value to set

 public FastpathArg(byte bytes[])
          
          Constructs an argument that consists of an array of bytes

        Parameters:
                bytes - array to store

 public FastpathArg(byte buf[],
                    int off,
                    int len)

           Constructs an argument that consists of part of a byte 
array

        Parameters:
                buf - source array
                off - offset within array
                len - length of data to include

 public FastpathArg(String s)
          
          Constructs an argument that consists of a String.
      
        Parameters:
                s - String to store

Geometric Data Types

PostgreSQL has a set of datatypes that can store geometric features 
into a table. These range from single points, lines, and polygons.

We support these types in Java with the postgresql.geometric package.

It contains classes that extend the postgresql.util.PGobject class. 
Refer to that class for details on how to implement your own data type 
handlers.

Class postgresql.geometric.PGbox

java.lang.Object
   |
   +----postgresql.util.PGobject
           |
           +----postgresql.geometric.PGbox

   public class PGbox extends PGobject implements Serializable, 
Cloneable

   This represents the box datatype within postgresql.

Variables

 public PGpoint point[]

          These are the two corner points of the box.

Constructors

 public PGbox(double x1,
              double y1,
              double x2,
              double y2)

        Parameters:
                x1 - first x coordinate
                y1 - first y coordinate
                x2 - second x coordinate
                y2 - second y coordinate

 public PGbox(PGpoint p1,
              PGpoint p2)

        Parameters:
                p1 - first point
                p2 - second point

 public PGbox(String s) throws SQLException
                            
        Parameters:
                s - Box definition in PostgreSQL syntax

        Throws: SQLException
                if definition is invalid
                
 public PGbox()

          Required constructor
              
Methods

 public void setValue(String value) throws SQLException
                
          This method sets the value of this object. It should be 
overidden, but still called by subclasses.
                            
        Parameters:
                value - a string representation of the value of the 
object
        Throws: SQLException
                thrown if value is invalid for this type

        Overrides:
                setValue in class PGobject

 public boolean equals(Object obj)

        Parameters:
                obj - Object to compare with
                
        Returns:
                true if the two boxes are identical
          
        Overrides:
                equals in class PGobject

 public Object clone()
        
          This must be overidden to allow the object to be cloned

        Overrides:
                clone in class PGobject
   
 public String getValue()
        
        Returns:
                the PGbox in the syntax expected by postgresql

        Overrides:
                getValue in class PGobject

Class postgresql.geometric.PGcircle

java.lang.Object
   |
   +----postgresql.util.PGobject
           |
           +----postgresql.geometric.PGcircle
        
   public class PGcircle extends PGobject implements Serializable, 
Cloneable
               
   This represents postgresql's circle datatype, consisting of a point 
and a radius

Variables

 public PGpoint center
           
          This is the centre point
 
public double radius
           
          This is the radius
   
Constructors   

 public PGcircle(double x,
                 double y,
                 double r)
          
        Parameters:
               x - coordinate of centre
                y - coordinate of centre
                r - radius of circle

 public PGcircle(PGpoint c,
                 double r)
          
        Parameters:
                c - PGpoint describing the circle's centre
                r - radius of circle

 public PGcircle(String s) throws SQLException

        Parameters:
                s - definition of the circle in PostgreSQL's syntax.

        Throws: SQLException
                on conversion failure

 public PGcircle()

          This constructor is used by the driver.
            
Methods   

 public void setValue(String s) throws SQLException

        Parameters:
                s - definition of the circle in PostgreSQL's syntax.

        Throws: SQLException
                on conversion failure

        Overrides:
                setValue in class PGobject

 public boolean equals(Object obj)

        Parameters:
                obj - Object to compare with
            
        Returns:
                true if the two boxes are identical

        Overrides:
                equals in class PGobject

 public Object clone()

          This must be overidden to allow the object to be cloned

        Overrides:
                clone in class PGobject

 public String getValue()

        Returns:
                the PGcircle in the syntax expected by postgresql
        
        Overrides:
                getValue in class PGobject

Class postgresql.geometric.PGline

java.lang.Object
   |
   +----postgresql.util.PGobject
           |
           +----postgresql.geometric.PGline

   public class PGline extends PGobject implements Serializable, 
Cloneable

   This implements a line consisting of two points. Currently line is 
not yet implemented in the backend, but this class ensures that when 
it's done were ready for it.

Variables
   
 public PGpoint point[]
     
          These are the two points.

Constructors

 public PGline(double x1,
               double y1,
               double x2,
               double y2)

        Parameters:
                x1 - coordinate for first point
                y1 - coordinate for first point
                x2 - coordinate for second point
                y2 - coordinate for second point

 public PGline(PGpoint p1,
               PGpoint p2)
     
        Parameters:
                p1 - first point
                p2 - second point

 public PGline(String s) throws SQLException
               
        Parameters:
                s - definition of the circle in PostgreSQL's syntax.

        Throws: SQLException
                on conversion failure

 public PGline()

          reuired by the driver
               
Methods

 public void setValue(String s) throws SQLException

        Parameters:
                s - Definition of the line segment in PostgreSQL's 
syntax

        Throws: SQLException
                on conversion failure

        Overrides:
                setValue in class PGobject
                
 public boolean equals(Object obj)

        Parameters:
                obj - Object to compare with
               
        Returns:
                true if the two boxes are identical
   
        Overrides:
                equals in class PGobject

 public Object clone()
        
          This must be overidden to allow the object to be cloned

        Overrides:
                clone in class PGobject

 public String getValue()
   
        Returns:
                the PGline in the syntax expected by postgresql
        
        Overrides:
                getValue in class PGobject

Class postgresql.geometric.PGlseg
             
java.lang.Object
   |
   +----postgresql.util.PGobject
           |
           +----postgresql.geometric.PGlseg
          
   public class PGlseg extends PGobject implements Serializable, 
Cloneable
 
   This implements a lseg (line segment) consisting of two points

Variables

 public PGpoint point[]
           
          These are the two points.

Constructors
   
 public PGlseg(double x1,
               double y1,
               double x2,
               double y2)
     
        Parameters:

                x1 - coordinate for first point
                y1 - coordinate for first point
                x2 - coordinate for second point
                y2 - coordinate for second point

 public PGlseg(PGpoint p1,
               PGpoint p2)
           
        Parameters:
                p1 - first point
                p2 - second point
   
 public PGlseg(String s) throws SQLException

        Parameters:
                s - definition of the circle in PostgreSQL's syntax.

        Throws: SQLException
                on conversion failure

 public PGlseg()

          reuired by the driver
               
Methods    
   
 public void setValue(String s) throws SQLException
   
        Parameters:
                s - Definition of the line segment in PostgreSQL's 
syntax

        Throws: SQLException
                on conversion failure
     
        Overrides:
                setValue in class PGobject
                
 public boolean equals(Object obj)

        Parameters:
                obj - Object to compare with
               
        Returns:
                true if the two boxes are identical
   
        Overrides:
                equals in class PGobject
   
 public Object clone()

          This must be overidden to allow the object to be cloned

        Overrides:
               clone in class PGobject

 public String getValue()

        Returns:
                the PGlseg in the syntax expected by postgresql
        
        Overrides:
                getValue in class PGobject

Class postgresql.geometric.PGpath
                                
java.lang.Object
   |
   +----postgresql.util.PGobject
           |
           +----postgresql.geometric.PGpath
          
   public class PGpath extends PGobject implements Serializable, 
Cloneable
               
   This implements a path (a multiple segmented line, which may be 
closed)
           
Variables

 public boolean open
               
          True if the path is open, false if closed

 public PGpoint points[]

          The points defining this path

Constructors   

 public PGpath(PGpoint points[],
               boolean open)
          
        Parameters:
                points - the PGpoints that define the path
                open - True if the path is open, false if closed

 public PGpath()

          Required by the driver

 public PGpath(String s) throws SQLException

        Parameters:
                s - definition of the circle in PostgreSQL's syntax.

        Throws: SQLException
                on conversion failure

Methods

 public void setValue(String s) throws SQLException
   
        Parameters:
                s - Definition of the path in PostgreSQL's syntax
           
        Throws: SQLException
                on conversion failure

        Overrides:
                setValue in class PGobject

 public boolean equals(Object obj)

        Parameters:
                obj - Object to compare with

        Returns:
                true if the two boxes are identical

        Overrides:
                equals in class PGobject

 public Object clone()

          This must be overidden to allow the object to be cloned

        Overrides:
                clone in class PGobject

 public String getValue()

          This returns the polygon in the syntax expected by 
postgresql

        Overrides:
                getValue in class PGobject

 public boolean isOpen()

     This returns true if the path is open

 public boolean isClosed()

     This returns true if the path is closed

 public void closePath()

     Marks the path as closed

 public void openPath()

     Marks the path as open

Class postgresql.geometric.PGpoint
                                
java.lang.Object
   |
   +----postgresql.util.PGobject
           |
           +----postgresql.geometric.PGpoint
          
   public class PGpoint extends PGobject implements Serializable, 
Cloneable

   This implements a version of java.awt.Point, except it uses double 
to represent the coordinates.

   It maps to the point datatype in postgresql.

Variables

 public double x

          The X coordinate of the point

 public double y

          The Y coordinate of the point

Constructors

 public PGpoint(double x,
                double y)

        Parameters:
                x - coordinate
                y - coordinate

 public PGpoint(String value) throws SQLException
     
          This is called mainly from the other geometric types, when a 
point is imbeded within their definition.
             
        Parameters:
                value - Definition of this point in PostgreSQL's 
syntax
   
 public PGpoint()
          
          Required by the driver

Methods

 public void setValue(String s) throws SQLException

        Parameters:
                s - Definition of this point in PostgreSQL's syntax

        Throws: SQLException
                on conversion failure

        Overrides:
                setValue in class PGobject
          
 public boolean equals(Object obj)

        Parameters:
                obj - Object to compare with

        Returns:
                true if the two boxes are identical

        Overrides:
                equals in class PGobject

 public Object clone()
                
          This must be overidden to allow the object to be cloned

        Overrides:
                clone in class PGobject
          
 public String getValue()       
    
        Returns:
                the PGpoint in the syntax expected by postgresql

        Overrides:
                getValue in class PGobject
          
 public void translate(int x,
                       int y)

          Translate the point with the supplied amount.

        Parameters:
                x - integer amount to add on the x axis
                y - integer amount to add on the y axis

 public void translate(double x,
                       double y)
          
          Translate the point with the supplied amount.
 
        Parameters:
                x - double amount to add on the x axis
                y - double amount to add on the y axis

 public void move(int x,
                  int y)
                
          Moves the point to the supplied coordinates.

        Parameters:
                x - integer coordinate
                y - integer coordinate

public void move(double x,
                  double y)
          
          Moves the point to the supplied coordinates.

        Parameters:
                x - double coordinate
                y - double coordinate

 public void setLocation(int x,
                         int y)

          Moves the point to the supplied coordinates. refer to
          java.awt.Point for description of this

        Parameters:
                x - integer coordinate
                y - integer coordinate

        See Also:
                Point

 public void setLocation(Point p)

          Moves the point to the supplied java.awt.Point refer to
          java.awt.Point for description of this

        Parameters:
                p - Point to move to

        See Also:
                Point

Class postgresql.geometric.PGpolygon
                                
java.lang.Object
   |
   +----postgresql.util.PGobject
           |
           +----postgresql.geometric.PGpolygon

   public class PGpolygon extends PGobject implements Serializable, 
Cloneable
               
   This implements the polygon datatype within PostgreSQL.

Variables

 public PGpoint points[]

          The points defining the polygon
                                
Constructors

 public PGpolygon(PGpoint points[])

          Creates a polygon using an array of PGpoints

        Parameters:
                points - the points defining the polygon

 public PGpolygon(String s) throws SQLException
                 
        Parameters:
                s - definition of the circle in PostgreSQL's syntax.

        Throws: SQLException
                on conversion failure

 public PGpolygon()

          Required by the driver

Methods

 public void setValue(String s) throws SQLException

        Parameters:
                s - Definition of the polygon in PostgreSQL's syntax

        Throws: SQLException
                on conversion failure

        Overrides:
                setValue in class PGobject

 public boolean equals(Object obj)
     
        Parameters:
                obj - Object to compare with
                                
        Returns:
                true if the two boxes are identical

        Overrides:
                equals in class PGobject

 public Object clone()
        
          This must be overidden to allow the object to be cloned

        Overrides:
                clone in class PGobject
                 
 public String getValue()

        Returns:
                the PGpolygon in the syntax expected by postgresql

        Overrides:
                getValue in class PGobject

Large Objects

Large objects are supported in the standard <acronym>JDBC</acronym> specification. 
However, that interface is limited, and the api provided by PostgreSQL 
allows for random access to the objects contents, as if it was a local 
file.

The postgresql.largeobject package profides to Java the libpq C 
interface's large object <acronym>API</acronym>. It consists of two classes, 
LargeObjectManager, which deals with creating, opening and deleting 
large obejects, and LargeObject which deals with an individual object.

Class postgresql.largeobject.LargeObject

java.lang.Object
   |
   +----postgresql.largeobject.LargeObject

public class LargeObject extends Object

This class implements the large object interface to postgresql.

   It provides the basic methods required to run the interface, plus a 
pair of methods that provide InputStream and OutputStream classes for 
this object.

   Normally, client code would use the getAsciiStream, 
getBinaryStream, or getUnicodeStream methods in ResultSet, or 
setAsciiStream, setBinaryStream, or setUnicodeStream methods in 
PreparedStatement to access Large Objects.

   However, sometimes lower level access to Large Objects are 
required, that are not supported by the <acronym>JDBC</acronym> specification.

   Refer to postgresql.largeobject.LargeObjectManager on how to gain 
access to a Large Object, or how to create one.

   See Also:
          LargeObjectManager

Variables

 public static final int SEEK_SET

          Indicates a seek from the begining of a file

 public static final int SEEK_CUR

          Indicates a seek from the current position

 public static final int SEEK_END

          Indicates a seek from the end of a file

Methods

 public int getOID()

        Returns:
                the OID of this LargeObject

 public void close() throws SQLException

          This method closes the object. You must not call methods in 
this object after this is called.

    Throws: SQLException
                if a database-access error occurs.

 public byte[] read(int len) throws SQLException

          Reads some data from the object, and return as a byte[] 
array

        Parameters:
                len - number of bytes to read

        Returns:
                byte[] array containing data read

        Throws: SQLException
                if a database-access error occurs.

 public void read(byte buf[],
                  int off,
                  int len) throws SQLException

          Reads some data from the object into an existing array

        Parameters:
                buf - destination array
                off - offset within array
                len - number of bytes to read

        Throws: SQLException
                if a database-access error occurs.

 public void write(byte buf[]) throws SQLException

          Writes an array to the object


        Parameters:
                buf - array to write

        Throws: SQLException
                if a database-access error occurs.

 public void write(byte buf[],
                   int off,
                   int len) throws SQLException

          Writes some data from an array to the object

        Parameters:
                buf - destination array
                off - offset within array
                len - number of bytes to write

        Throws: SQLException
                if a database-access error occurs.

 public void seek(int pos,
                  int ref) throws SQLException

          Sets the current position within the object.

          This is similar to the fseek() call in the standard C 
library.It allows you to have random access to the large object.

        Parameters:
                pos - position within object
                ref - Either SEEK_SET, SEEK_CUR or SEEK_END
        Throws: SQLException
                if a database-access error occurs.

 public void seek(int pos) throws SQLException

          Sets the current position within the object.

          This is similar to the fseek() call in the standard C 
library.It allows you to have random access to the large object.

        Parameters:
                pos - position within object from begining

        Throws: SQLException
                if a database-access error occurs.

 public int tell() throws SQLException

        Returns:
                the current position within the object

        Throws: SQLException
                if a database-access error occurs.

 public int size() throws SQLException

          This method is inefficient, as the only way to find out the 
size of the object is to seek to the end, record the current position, 
then return to the original position.

          A better method will be found in the future.

        Returns:
                the size of the large object

        Throws: SQLException
                if a database-access error occurs.

 public InputStream getInputStream() throws SQLException

          Returns an InputStream from this object.

          This InputStream can then be used in any method that 
requires an InputStream.

        Throws: SQLException
                if a database-access error occurs.

 public OutputStream getOutputStream() throws SQLException

          Returns an OutputStream to this object

          This OutputStream can then be used in any method that 
requires an OutputStream.

        Throws: SQLException
                if a database-access error occurs.

Class postgresql.largeobject.LargeObjectManager
                                
java.lang.Object
   |
   +----postgresql.largeobject.LargeObjectManager

public class LargeObjectManager extends Object

This class implements the large object interface to postgresql.
        
   It provides methods that allow client code to create, open and 
delete large objects from the database. When opening an object, an 
instance of postgresql.largeobject.LargeObject is returned, and its 
methods then allow access to the object.

This class can only be created by postgresql.Connection

To get access to this class, use the following segment of code:

 import postgresql.largeobject.*;
 Connection  conn;
 LargeObjectManager lobj;
 ... code that opens a connection ...
 lobj = ((postgresql.Connection)myconn).getLargeObjectAPI();

Normally, client code would use the getAsciiStream, getBinaryStream, 
or getUnicodeStream methods in ResultSet, or setAsciiStream, 
setBinaryStream, or setUnicodeStream methods in PreparedStatement to 
access Large Objects.

   However, sometimes lower level access to Large Objects are 
required, that are not supported by the <acronym>JDBC</acronym> specification.

   Refer to postgresql.largeobject.LargeObject on how to manipulate 
the contents of a Large Object.

   See Also:
          LargeObject

Variables

 public static final int WRITE

          This mode indicates we want to write to an object

 public static final int READ

          This mode indicates we want to read an object

 public static final int READWRITE

          This mode is the default. It indicates we want read and 
write access to a large object

Methods

 public LargeObject open(int oid) throws SQLException
          
          This opens an existing large object, based on its OID. This
          method assumes that READ and WRITE access is required (the 
default).

        Parameters:
                oid - of large object

        Returns:
                LargeObject instance providing access to the object

        Throws: SQLException
                on error

 public LargeObject open(int oid,
                         int mode) throws SQLException
          
          This opens an existing large object, based on its OID
  
        Parameters:
                oid - of large object
                mode - mode of open

        Returns:
                LargeObject instance providing access to the object

        Throws: SQLException
                on error

 public int create() throws SQLException

          This creates a large object, returning its OID.

          It defaults to READWRITE for the new object's attributes.

        Returns:
                oid of new object

        Throws: SQLException
                on error

 public int create(int mode) throws SQLException

          This creates a large object, returning its OID

        Parameters:
                mode - a bitmask describing different attributes of 
the
                new object

        Returns:
                oid of new object

        Throws: SQLException
                on error

 public void delete(int oid) throws SQLException
          
          This deletes a large object.
          
        Parameters:
                oid - describing object to delete

        Throws: SQLException
                on error

 public void unlink(int oid) throws SQLException

          This deletes a large object.

          It is identical to the delete method, and is supplied as the 
C <acronym>API</acronym> uses unlink.

        Parameters:
                oid - describing object to delete

        Throws: SQLException
                on error

Object Serialisation
PostgreSQL is not a normal SQL Database. It is far more extensible 
than most other databases, and does support Object Oriented features 
that are unique to it. 

One of the consequences of this, is that you can have one table refer 
to a row in another table. For example:

test=> create table users (username name,fullname text);
CREATE
test=> create table server (servername name,adminuser users);
CREATE
test=> insert into users values ('peter','Peter Mount');
INSERT 2610132 1
test=> insert into server values ('maidast',2610132::users);
INSERT 2610133 1
test=> select * from users;
username|fullname      
--------+--------------
peter   |Peter Mount   
(1 row)

test=> select * from server;
servername|adminuser
----------+---------
maidast   |  2610132
(1 row)

Ok, the above example shows that we can use a table name as a field, 
and the row's oid value is stored in that field.

What does this have to do with Java?

In Java, you can store an object to a Stream as long as it's class 
implements the java.io.Serializable interface. This process, known as 
Object Serialization, can be used to store complex objects into the 
database.

Now, under <acronym>JDBC</acronym>, you would have to use a LargeObject to store them. 
However, you cannot perform queries on those objects.

What the postgresql.util.Serialize class does, is provide a means of 
storing an object as a table, and to retrieve that object from a 
table. In most cases, you would not need to access this class direct, 
but you would use the PreparedStatement.setObject() and 
ResultSet.getObject() methods. Those methods will check the objects 
class name against the table's in the database. If a match is found, 
it assumes that the object is a Serialized object, and retrieves it 
from that table. As it does so, if the object contains other 
serialized objects, then it recurses down the tree.

Sound's complicated? In fact, it's simpler than what I wrote - it's 
just difficult to explain.

The only time you would access this class, is to use the create() 
methods. These are not used by the driver, but issue one or more 
"create table" statements to the database, based on a Java Object or 
Class that you want to serialize.

Oh, one last thing. If your object contains a line like:

     public int oid;

then, when the object is retrieved from the table, it is set to the 
oid within the table. Then, if the object is modified, and re-
serialized, the existing entry is updated.

If the oid variable is not present, then when the object is 
serialized, it is always inserted into the table, and any existing 
entry in the table is preserved.

Setting oid to 0 before serialization, will also cause the object to 
be inserted. This enables an object to be duplicated in the database.

Class postgresql.util.Serialize

java.lang.Object
   |
   +----postgresql.util.Serialize

   public class Serialize extends Object

   This class uses PostgreSQL's object oriented features to store Java 
Objects. It does this by mapping a Java Class name to a table in the 
database. Each entry in this new table then represents a Serialized 
instance of this class. As each entry has an OID (Object IDentifier), 
this OID can be included in another table. This is too complex to show 
here, and will be documented in the main documents in more detail.

Constructors

 public Serialize(Connection c,
                  String type) throws SQLException

          This creates an instance that can be used to serialize 
ordeserialize a Java object from a PostgreSQL table.

Methods

 public Object fetch(int oid) throws SQLException

          This fetches an object from a table, given it's OID

        Parameters:
                oid - The oid of the object

        Returns:
                Object relating to oid

        Throws: SQLException
                on error

 public int store(Object o) throws SQLException

          This stores an object into a table, returning it's OID.

          If the object has an int called OID, and it is > 0, then 
that value is used for the OID, and the table will be updated. If the 
value of OID is 0, then a new row will be created, and the value of 
OID will be set in the object. This enables an object's value in the 
database to be updateable. If the object has no int called OID, then 
the object is stored. However if the object is later retrieved, 
amended and stored again, it's new state will be appended to the 
table, and will not overwrite the old entries.

        Parameters:
                o - Object to store (must implement Serializable)

        Returns:
                oid of stored object

        Throws: SQLException
                on error
 
 public static void create(Connection con,
                           Object o) throws SQLException

          This method is not used by the driver, but it creates a 
table, given a Serializable Java Object. It should be used before 
serializing any objects.

        Parameters:
                c - Connection to database
                o - Object to base table on

        Throws: SQLException
                on error

                   Returns:
                Object relating to oid

        Throws: SQLException
                on error

 public int store(Object o) throws SQLException

          This stores an object into a table, returning it's OID.

          If the object has an int called OID, and it is > 0, then 
that value is used for the OID, and the table will be updated. If the 
value of OID is 0, then a new row will be created, and the value of 
OID will be set in the object. This enables an object's value in the 
database to be updateable. If the object has no int called OID, then 
the object is stored. However if the object is later retrieved, 
amended and stored again, it's new state will be appended to the 
table, and will not overwrite the old entries.

        Parameters:
                o - Object to store (must implement Serializable)

        Returns:
                oid of stored object

        Throws: SQLException
                on error
 
 public static void create(Connection con,
                           Object o) throws SQLException

          This method is not used by the driver, but it creates a 
table, given a Serializable Java Object. It should be used before 
serializing any objects.

        Parameters:
                c - Connection to database
                o - Object to base table on

        Throws: SQLException
                on error
                
 public static void create(Connection con,
                           Class c) throws SQLException

          This method is not used by the driver, but it creates a 
table, given a Serializable Java Object. It should be used before 
serializing any objects.

        Parameters:
                c - Connection to database
                o - Class to base table on

        Throws: SQLException
                on error

 public static String toPostgreSQL(String name) throws SQLException
          
          This converts a Java Class name to a postgresql table, by
          replacing . with _

          Because of this, a Class name may not have _ in the name.

          Another limitation, is that the entire class name (including
          packages) cannot be longer than 31 characters (a limit 
forced by PostgreSQL).

        Parameters:
                name - Class name

        Returns:
                PostgreSQL table name

        Throws: SQLException
                on error
          
 public static String toClassName(String name) throws SQLException

          This converts a postgresql table to a Java Class name, by
          replacing _ with .

        Parameters:
                name - PostgreSQL table name
  
        Returns:
                Class name

        Throws: SQLException
                on error

Utility Classes

The postgresql.util package contains classes used by the internals of 
the main driver, and the other extensions.

Class postgresql.util.PGmoney
                                
java.lang.Object
   |
   +----postgresql.util.PGobject
           |
           +----postgresql.util.PGmoney

   public class PGmoney extends PGobject implements Serializable, 
Cloneable
               
   This implements a class that handles the PostgreSQL money type

Variables

 public double val
                                
          The value of the field

Constructors
           
 public PGmoney(double value)
   
        Parameters:
                value - of field
               
 public PGmoney(String value) throws SQLException
   
          This is called mainly from the other geometric types, when a 
point is imbeded within their definition.

        Parameters:
                value - Definition of this point in PostgreSQL's 
syntax

 public PGmoney()

          Required by the driver

Methods

 public void setValue(String s) throws SQLException

        Parameters:
                s - Definition of this point in PostgreSQL's syntax

        Throws: SQLException
                on conversion failure

        Overrides:
                setValue in class PGobject

 public boolean equals(Object obj)

        Parameters:
                obj - Object to compare with
                                
        Returns:
                true if the two boxes are identical

        Overrides:
                equals in class PGobject

 public Object clone()
                
          This must be overidden to allow the object to be cloned

        Overrides:
                clone in class PGobject

 public String getValue()

        Returns:
                the PGpoint in the syntax expected by postgresql

        Overrides:
                getValue in class PGobject

Class postgresql.util.PGobject

java.lang.Object
   |
   +----postgresql.util.PGobject

   public class PGobject extends Object implements Serializable, 
Cloneable
               
   This class is used to describe data types that are unknown by
     <acronym>JDBC</acronym> 
Standard.
    A call to postgresql.Connection permits a class that extends this 
class to be associated with a named type. This is how the 
postgresql.geometric package operates.
    ResultSet.getObject() will return this class for any type that is 
not recognised on having it's own handler. Because of this, any 
postgresql data type is supported.

Constructors

 public PGobject()

          This is called by postgresql.Connection.getObject() to 
create the object.

Methods

 public final void setType(String type)

          This method sets the type of this object.

          It should not be extended by subclasses, hence its final

        Parameters:
                type - a string describing the type of the object

 public void setValue(String value) throws SQLException

          This method sets the value of this object. It must be 
overidden.

        Parameters:
                value - a string representation of the value of the
                object

        Throws: SQLException
                thrown if value is invalid for this type
    
 public final String getType()

          As this cannot change during the life of the object, it's 
final.

        Returns:
                the type name of this object

 public String getValue()

          This must be overidden, to return the value of the object, 
in the form required by postgresql.

        Returns:
                the value of this object

 public boolean equals(Object obj)

          This must be overidden to allow comparisons of objects

        Parameters:
                obj - Object to compare with

        Returns:
                true if the two boxes are identical

        Overrides:
                equals in class Object

 public Object clone()

          This must be overidden to allow the object to be cloned

        Overrides:
                clone in class Object

 public String toString()

          This is defined here, so user code need not overide it.
          
        Returns:
                the value of this object, in the syntax expected by 
postgresql

        Overrides:
                toString in class Object

Class postgresql.util.PGtokenizer

java.lang.Object
   |
   +----postgresql.util.PGtokenizer

   public class PGtokenizer extends Object

   This class is used to tokenize the text output of postgres.

   We could have used StringTokenizer to do this, however, we needed 
to handle nesting of '(' ')' '[' ']' '<' and '>' as these are used by 
the geometric data types.

   It's mainly used by the geometric classes, but is useful in parsing 
any output from custom data types output from postgresql.
                 
   See Also:
          PGbox, PGcircle, PGlseg, PGpath, PGpoint, PGpolygon
          
Constructors

 public PGtokenizer(String string,
                    char delim)

          Create a tokeniser.

        Parameters:
                string - containing tokens
                delim - single character to split the tokens

Methods
        
 public int tokenize(String string,
                     char delim)

          This resets this tokenizer with a new string and/or 
delimiter.

        Parameters:
                string - containing tokens
                delim - single character to split the tokens

 public int getSize()

        Returns:
                the number of tokens available

 public String getToken(int n)

        Parameters:
                n - Token number ( 0 ... getSize()-1 )

        Returns:
                The token value

 public PGtokenizer tokenizeToken(int n,
                                  char delim)

          This returns a new tokenizer based on one of our tokens. The 
geometric datatypes use this to process nested tokens (usually 
PGpoint).

        Parameters:
                n - Token number ( 0 ... getSize()-1 )
                delim - The delimiter to use

        Returns:
                A new instance of PGtokenizer based on the token

 public static String remove(String s,
                             String l,
                             String t)

          This removes the lead/trailing strings from a string

        Parameters:
                s - Source string
                l - Leading string to remove
                t - Trailing string to remove
                
        Returns:
                String without the lead/trailing strings

 public void remove(String l,
                    String t)

          This removes the lead/trailing strings from all tokens

        Parameters:
                l - Leading string to remove
                t - Trailing string to remove

 public static String removePara(String s)

          Removes ( and ) from the beginning and end of a string

        Parameters:
                s - String to remove from

        Returns:
                String without the ( or )

 public void removePara()

          Removes ( and ) from the beginning and end of all tokens

        Returns:
                String without the ( or )

 public static String removeBox(String s)
   
          Removes [ and ] from the beginning and end of a string

        Parameters:
                s - String to remove from
   
        Returns:
                String without the [ or ]

 public void removeBox()

          Removes [ and ] from the beginning and end of all tokens

        Returns:
                String without the [ or ]

 public static String removeAngle(String s)

          Removes < and > from the beginning and end of a string

        Parameters:
                s - String to remove from

        Returns:
                String without the < or >

 public void removeAngle()

          Removes < and > from the beginning and end of all tokens

        Returns:
                String without the < or >

Class postgresql.util.Serialize

This was documented earlier under Object Serialisation.

Class postgresql.util.UnixCrypt
              
java.lang.Object
   |
   +----postgresql.util.UnixCrypt

   public class UnixCrypt extends Object

   This class provides us with the ability to encrypt passwords when 
sent over the network stream

   Contains static methods to encrypt and compare passwords with Unix 
encrypted passwords.

   See John Dumas's Java Crypt page for the original source.

   http://www.zeh.com/local/jfd/crypt.html

Methods

 public static final String crypt(String salt,
                                  String original)

          Encrypt a password given the cleartext password and a 
"salt".
   
        Parameters:
                salt - A two-character string representing the salt 
used
                to iterate the encryption engine in lots of different
                ways. If you are generating a new encryption then this
                value should be randomised.
                original - The password to be encrypted.

        Returns:
                A string consisting of the 2-character salt followed 
by
                the encrypted password.
              
 public static final String crypt(String original)

          Encrypt a password given the cleartext password. This method 
generates a random salt using the 'java.util.Random' class.

        Parameters:
                original - The password to be encrypted.
   
        Returns: 
                A string consisting of the 2-character salt followed 
by
                the encrypted password.
               
 public static final boolean matches(String encryptedPassword,
                                     String enteredPassword)
                 
          Check that enteredPassword encrypts to encryptedPassword.
               
        Parameters:
                encryptedPassword - The encryptedPassword. The first 
two characters are assumed to be the salt. This string would be the 
same as one found in a Unix /etc/passwd file.
                enteredPassword - The password as entered by the user 
(or otherwise aquired).

        Returns:
                true if the password should be considered correct.

Using the driver in a multi Threaded or Servlet environment

A problem with many <acronym>JDBC</acronym> drivers, is that only one thread can use a 
Connection at any one time - otherwise a thread could send a query 
while another one is receiving results, and this would be a bad thing 
for the database engine.

PostgreSQL 6.4, brings thread safety to the entire driver. Standard 
<acronym>JDBC</acronym> was thread safe in 6.3.x, but the Fastpath
     <acronym>API</acronym> wasn't.

So, if your application uses multiple threads (which most decent ones 
would), then you don't have to worry about complex schemes to ensure 
only one uses the database at any time.

If a thread attempts to use the connection while another is using it, 
it will wait until the other thread has finished it's current 
operation.

If it's a standard SQL statement, then the operation is sending the 
statement, and retrieving any ResultSet (in full).

If it's a Fastpath call (ie: reading a block from a LargeObject), then 
it's the time to send, and retrieve that block.

This is fine for applications & applets, but can cause a performance 
problem with servlets.

With servlets, you can have a heavy load on the connection. If you 
have several threads performing queries, then each one will pause, 
which may not be what you are after.

To solve this, you would be advised to create a pool of Connections.

When ever a thread needs to use the database, it asks a manager class 
for a Connection. It hands a free connection to the thread, and marks 
it as busy. If a free connection is not available, it opens one.

Once the thread has finished with it, it returns it to the manager, 
who can then either close it, or add it to the pool. The manager would 
also check that the connection is still alive, and remove it from the 
pool if it's dead.

So, with servlets, it's up to you to use either a single connection, 
or a pool. The plus side for a pool is that threads will not be hit by 
the bottle neck caused by a single network connection. The down side, 
is that it increases the load on the server, as a backend is created 
for each Connection.

It's up to you, and your applications requirements.
</programlisting>
</para>
</sect1>

<sect1 id="jdbc-reading">
<title>Further Reading</title>

<para>
If you have not yet read it, I'd advise you read the <acronym>JDBC</acronym>
 <acronym>API</acronym> 
Documentation (supplied with Sun's <acronym>JDK</acronym>),
 and the <acronym>JDBC</acronym> Specification. 
Both are available on 
<ulink url="http://www.javasoft.com">JavaSoft's web site</ulink>.
</para>

<para>
<ulink url="http://www.retep.org.uk">My own web site</ulink>
 contains updated information not included in this 
document, and also includes precompiled drivers for v6.4, and earlier.
</para>
</sect1>
</chapter>

<!-- Keep this comment at the end of the file
Local variables:
mode:sgml
sgml-omittag:nil
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
sgml-parent-document:nil
sgml-default-dtd-file:"./reference.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:("/usr/lib/sgml/catalog")
sgml-local-ecat-files:nil
End:
-->