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 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383
|
<?xml version="1.0"?>
<!--
Copyright (c) 2004-2011, PostgreSQL Global Development Group
-->
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd">
<book id="jdbc">
<title>The <productname>PostgreSQL</productname> <acronym>JDBC</acronym> Interface</title>
<chapter id="intro">
<title>Introduction</title>
<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>
<productname>PostgreSQL</productname> 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 system's own network protocol. Because of this, the driver
is platform independent; once compiled, the driver can be used on
any system.
</para>
<para>
This manual 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.
</para>
</chapter>
<chapter id="setup">
<title>Setting up the <acronym>JDBC</acronym> Driver</title>
<para>
This section describes the steps you need to take before you can
write or run programs that use the <acronym>JDBC</acronym> interface.
</para>
<sect1 id="build">
<title>Getting the Driver</title>
<para>
Precompiled versions of the driver can be downloaded from
the <ulink
url="http://jdbc.postgresql.org"><productname>PostgreSQL</productname>
<acronym>JDBC</acronym> web site</ulink>.
</para>
<para>
Alternatively you can build the driver from source, but you should
only need to do this if you are making changes to the source code.
To build the <acronym>JDBC</acronym> driver, you need
<application>Ant</application> 1.5 or higher and a <acronym>JDK</acronym>.
<application>Ant</application> is a special tool for building
Java-based packages. It can be downloaded from the <ulink
url="http://ant.apache.org/index.html"><application>Ant</application>
web site</ulink>.
</para>
<para>
If you have several Java compilers installed, it depends on the
Ant configuration which one gets used. Precompiled
<application>Ant</application> distributions are typically set up
to read a file <filename>.antrc</filename> in the current user's
home directory for configuration. For example, to use a different
<acronym>JDK</acronym> than the default, this may work:
<programlisting>
JAVA_HOME=/usr/local/jdk1.6.0_07
JAVACMD=$JAVA_HOME/bin/java
</programlisting>
</para>
<para>
To compile the driver simply run <command>ant</command> in the top level
directory. The compiled driver will be placed in <filename>jars/postgresql.jar</filename>.
The resulting driver will be built for the version of Java you are
running. If you build with a 1.4 or 1.5
<acronym>JDK</acronym> you will build a version that supports the
<acronym>JDBC</acronym> 3 specification and if you build
with a 1.6 or higher <acronym>JDK</acronym> you will build a version that
supports the <acronym>JDBC</acronym> 4 specification.
</para>
</sect1>
<sect1 id="classpath">
<title>Setting up the Class Path</title>
<indexterm zone="classpath">
<primary>class path</primary>
</indexterm>
<indexterm zone="classpath">
<primary>CLASSPATH</primary>
</indexterm>
<para>
To use the driver, the JAR archive (named
<filename>postgresql.jar</filename> if you built from source, otherwise
it will likely be named with the following convention:
<filename>postgresql-<replaceable>[server version]</replaceable>.<replaceable>[buildnumber]</replaceable>.jdbc<replaceable>[JDBC version]</replaceable>.jar</filename>,
for example <filename>postgresql-8.0-310.jdbc3.jar</filename>)
needs to be included in the class path, either by putting it in the
<envar>CLASSPATH</envar> environment variable, or by using flags on the
<command>java</command> command line.
</para>
<para>
For instance, assume we have an application that uses the
<acronym>JDBC</acronym> driver to access a database, and that
application is installed as
<filename>/usr/local/lib/myapp.jar</filename>. The
<productname>PostgreSQL</productname> <acronym>JDBC</acronym> driver installed as
<filename>/usr/local/pgsql/share/java/postgresql.jar</filename>. To run
the application, we would use:
<programlisting>
export CLASSPATH=/usr/local/lib/myapp.jar:/usr/local/pgsql/share/java/postgresql.jar:.
java MyApp
</programlisting>
</para>
<para>
Loading the driver from within the application is covered in
<xref linkend="use"/>.
</para>
</sect1>
<sect1 id="prepare">
<title>Preparing the Database Server for <acronym>JDBC</acronym></title>
<para>
Because Java does not support using unix sockets the
<productname>PostgreSQL</productname> server must be configured to
allow <acronym>TCP/IP</acronym> connections. Starting with server
version 8.0 <acronym>TCP/IP</acronym> connections are allowed from
<literal>localhost</literal>. To allow connections to other interfaces
than the loopback interface, you must modify the
<filename>postgresql.conf</filename> file's
<literal>listen_addresses</literal> setting.
</para>
<para>
For server versions prior to 8.0 the server does not listen on any
interface by default, and you must set
<literal>tcpip_socket = true</literal> in the
<filename>postgresql.conf</filename> file.
</para>
<para>
Once you have made sure the server is correctly listening for
<acronym>TCP/IP</acronym> connections the next step is to verify
that users are allowed to connect to the server. Client authentication
is setup in <filename>pg_hba.conf</filename>.
Refer to the main <productname>PostgreSQL</productname> documentation for
details. The <acronym>JDBC</acronym> driver supports the
<literal>trust</literal>, <literal>ident</literal>,
<literal>password</literal>, <literal>md5</literal>, and
<literal>crypt</literal> authentication methods.
</para>
</sect1>
<sect1 id="your-database">
<title>Creating a Database</title>
<para>
When creating a database to be accessed via <acronym>JDBC</acronym>
it is important to select an appropriate encoding for your data. Many
other client interfaces do not care what data you send back and forth,
and will allow you to do inappropriate things, but Java makes sure that
your data is correctly encoded. Do not use a database that uses the
<literal>SQL_ASCII</literal> encoding. This is not a real
encoding and you will have problems the moment you store data in it that
does not fit in the seven bit <acronym>ASCII</acronym> character set.
If you do not know what your encoding will be or are otherwise unsure
about what you will be storing the <literal>UTF8</literal> encoding
is a reasonable default to use.
</para>
</sect1>
</chapter>
<chapter id="use">
<title>Initializing the Driver</title>
<para>
This section describes how to load and initialize the <acronym>JDBC</acronym>
driver in your programs.
</para>
<sect1 id="import">
<title>Importing <acronym>JDBC</acronym></title>
<para>
Any source that uses <acronym>JDBC</acronym> needs to import the
<literal>java.sql</literal> package, using:
<programlisting>
import java.sql.*;
</programlisting>
</para>
<note>
<para>
You should not import the <literal>org.postgresql</literal> package
unless you are using not standard <productname>PostgreSQL</productname>
extensions to the <acronym>JDBC</acronym> <acronym>API</acronym>.
</para>
</note>
</sect1>
<sect1 id="load">
<title>Loading the Driver</title>
<note>
<para>
Starting from Java 6.0 it is enough to add the postgresql driver to the class path
because the <productname>PostgreSQL</productname> <acronym>JDBC</acronym>
driver supports the new auto-loading feature. You can safely ignore rest of the section.
</para>
</note>
<para>
In Java 5.0 or older, before you can connect to a database, you need to load the
driver. There are two methods available, and it depends on your
code which is 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 <productname>PostgreSQL</productname>, 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>
<note>
<para>
The <function>forName()</function> method can throw a
<classname>ClassNotFoundException</classname> if the driver is
not available.
</para>
</note>
<para>
This is the most common method to use, but restricts your code to
use just <productname>PostgreSQL</productname>. If your code may
access another database system in the future, and you do not use
any <productname>PostgreSQL</productname>-specific extensions, then
the second method is advisable.
</para>
<para>
The second method passes the driver as a parameter to the
<acronym>JVM</acronym> as it starts, using the <option>-D</option>
argument. Example:
<programlisting>
java -Djdbc.drivers=org.postgresql.Driver example.ImageViewer
</programlisting>
In this example, the <acronym>JVM</acronym> will attempt to load
the driver as part of its initialization. Once done, the
<classname>ImageViewer</classname> is started.
</para>
<para>
Now, this method is the better one to use because it allows your
code to be used with other database packages without recompiling
the code. The only thing that would also change is the connection
<acronym>URL</acronym>, which is covered next.
</para>
<para>
One last thing: When your code then tries to open a
<classname>Connection</classname>, and you get a <errorname>No
driver available</errorname> <classname>SQLException</classname>
being thrown, this is probably caused by the driver not being in
the class path, or the value in the parameter not being correct.
</para>
</sect1>
<sect1 id="connect">
<title>Connecting to the Database</title>
<para>
With <acronym>JDBC</acronym>, a database is represented by a
<acronym>URL</acronym> (Uniform Resource Locator). With
<productname>PostgreSQL</productname>, this takes one of the
following forms:
<itemizedlist>
<listitem>
<synopsis>
jdbc:postgresql:<replaceable class="parameter">database</replaceable>
</synopsis>
</listitem>
<listitem>
<synopsis>
jdbc:postgresql://<replaceable class="parameter">host</replaceable>/<replaceable class="parameter">database</replaceable>
</synopsis>
</listitem>
<listitem>
<synopsis>
jdbc:postgresql://<replaceable class="parameter">host</replaceable>:<replaceable class="parameter">port</replaceable>/<replaceable class="parameter">database</replaceable>
</synopsis>
</listitem>
</itemizedlist>
The parameters have the following meanings:
<variablelist>
<varlistentry>
<term>
<replaceable class="parameter">host</replaceable>
</term>
<listitem>
<para>
The host name of the server. Defaults to <literal>localhost</literal>.
To specify an IPv6 address your must enclose the
<replaceable class="parameter">host</replaceable> parameter
with square brackets, for example:
<programlisting>
jdbc:postgresql://[::1]:5740/accounting
</programlisting>
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<replaceable class="parameter">port</replaceable>
</term>
<listitem>
<para>
The port number the server is listening on. Defaults to the
<productname>PostgreSQL</productname> 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 <classname>Connection</classname> instance from
<acronym>JDBC</acronym>. To do this,
you use the <function>DriverManager.getConnection()</function> method:
<programlisting>
Connection db = DriverManager.getConnection(url, username, password);
</programlisting>
</para>
<sect2 id="connection-parameters">
<title>Connection Parameters</title>
<para>
In addition to the standard connection parameters the driver supports a
number of additional properties which can be used to specify additional
driver behavior specific to <productname>PostgreSQL</productname>. These
properties may be specified in either the connection
<acronym>URL</acronym> or an additional
<classname>Properties</classname> object parameter to
<function>DriverManager.getConnection</function>. The following
examples illustrate the use of both methods to establish a SSL
connection.
<programlisting>
String url = "jdbc:postgresql://localhost/test";
Properties props = new Properties();
props.setProperty("user","fred");
props.setProperty("password","secret");
props.setProperty("ssl","true");
Connection conn = DriverManager.getConnection(url, props);
</programlisting>
<programlisting>
String url = "jdbc:postgresql://localhost/test?user=fred&password=secret&ssl=true";
Connection conn = DriverManager.getConnection(url);
</programlisting>
<variablelist>
<varlistentry>
<term><varname>user</varname> = <type>String</type></term>
<listitem>
<para>
The database user on whose behalf the connection is being made.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>password</varname> = <type>String</type></term>
<listitem>
<para>
The database user's password.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>ssl</varname></term>
<listitem>
<para>
Connect using <acronym>SSL</acronym>. The driver must have been
compiled with <acronym>SSL</acronym> support. This property does
not need a value associated with it. The mere presence of it
specifies a <acronym>SSL</acronym> connection. However, for
compatibility with future versions, the value "true" is
preferred. For more information see <xref linkend="ssl" />.
</para>
<para>Alternatively <literal>sslmode</literal> can be used.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>sslmode</varname></term>
<listitem>
<para>
Parameter governing the use of <acronym>SSL</acronym>. Similar to the
libpq parameter, the allowed values are disable, require, verify-ca,
verify-full. (allow and require are not implemented.)
The use of parameter <literal>ssl</literal> is discouraged, as sslmode
can cover all the possibilities, however, if sslmode is not
set, the driver's behaviour is backward compatible.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>sslcert</varname></term>
<listitem>
<para>
The location of the client's <acronym>SSL</acronym> certificate.
The file format is compatible with libpq. If missing, the default
locations are looked up (in $HOME/.postgresql under Linux).
In some cases it is desirable
to supress loading the default client certificate (and any other one),
in this case specify sslcert with an empty argument.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>sslrootcert</varname></term>
<listitem>
<para>
The location of the root certificate for authenticating the server.
The file format is compatible with libpq. If missing, the default
locations are looked up (in $HOME/.postgresql under Linux).
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>sslkey</varname></term>
<listitem>
<para>
The location of the client's <acronym>SSL</acronym> key.
The file must be in PKCS#8 format.
The conversion can be made
by the following openssl command:
<programlisting>
openssl pkcs8 -topk8 -in client.key -out client.pk8 -outform DER -v1 PBE-SHA1-3DES
</programlisting>
the ciphers, recognized by java are PBE-MD5-DES, PBE-SHA1-3DES,
PBE-SHA1-RC2-40,
or with the -nocrypt switch, it can be unencrypted.
If missing, the default
locations are looked up (in $HOME/.postgresql under Linux).
The default filename for the key is postgresql.pk8
instead of postgresql.key to allow simultaneous use of the jdbc driver
and other libpq compatible applications.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>sslpassword</varname></term>
<listitem>
<para>
The password for the client's ssl key (different from the database password).
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>sslpasswordcallback</varname></term>
<listitem>
<para>
A class, implementing
<classname>javax.security.auth.callback.CallbackHandler</classname>
that can handle PassworCallback for the ssl password. If set,
sslpassword is ignored.
The supplied class must have either a constructor with a Properties
argument where
the connection info properties are given, or a zero argument constructor
If neither sslpassword nor sslpasswordcallback is set, and the key is
protected,
the user is prompted at the console for a password
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>sslhostnameverifier</varname></term>
<listitem>
<para>
A class, <classname>implementing javax.net.ssl.HostnameVerifier</classname>
that can verify the server. The supplied class must have either a
constructor
with a Properties argument where the connection info properties are given,
or a zero argument constructor. If set the server hostname is verified
irrespective
of the value of sslmode.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>sslfactory</varname> = <type>String</type></term>
<listitem>
<para>
The provided value is a class name to use as the
<classname>SSLSocketFactory</classname> when establishing a
<acronym>SSL</acronym> connection.
For more information see <xref linkend="ssl-factory"/>.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>sslfactoryarg</varname> = <type>String</type></term>
<listitem>
<para>
This value is an optional argument to the constructor of the
<literal>sslfactory</literal> class provided above.
For more information see <xref linkend="ssl-factory"/>.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>compatible</varname> = <type>String</type></term>
<listitem>
<para>
Act like an older version of the driver to retain compatibility with
older applications. At the moment this controls two driver behaviours:
the handling of binary data fields, and the handling of parameters set
via <function>setString()</function>
</para>
<para>
Older versions of the driver used this property to also control the
protocol used to connect to the backend. This is now controlled by the
<varname>protocolVersion</varname> property.
</para>
<para>
Information on binary data handling is detailed in
<xref linkend="binary-data" />. To force the use of
Large Objects set the compatible property to 7.1.
</para>
<para>
When <varname>compatible</varname> is set to <literal>7.4</literal> or
below, the default for the <varname>stringtype</varname> parameter is
changed to <literal>unspecified</literal>.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>protocolVersion</varname> = <type>String</type></term>
<listitem>
<para>
The driver supports both the V2 and V3 frontend/backend protocols.
The V3 protocol was introduced in 7.4 and the driver will by default
try to connect using the V3 protocol, if that fails it will fall
back to the V2 protocol. If the protocolVersion property is
specified, the driver will try only the specified protocol (which
should be either "2" or "3"). Setting protocolVersion to "2" may
be used to avoid the failed attempt to use the V3 protocol when
connecting to a version 7.3 or earlier server, or to force the
driver to use the V2 protocol despite connecting to a 7.4 or greater
server.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>loglevel</varname> = <type>int</type></term>
<listitem>
<para>
Set the amount of logging information printed to the DriverManager's
current value for LogStream or LogWriter. It currently supports
values of <literal>org.postgresql.Driver.DEBUG</literal> (2) and
<literal>org.postgresql.Driver.INFO</literal> (1).
<literal>INFO</literal> will log very little information while
<literal>DEBUG</literal> will produce significant detail. This
property is only really useful if you are a developer or are
having problems with the driver.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>charSet</varname> = <type>String</type></term>
<listitem>
<para>
The character set to use for data sent to the database or recieved
from the database. This property is only relevent for server
versions less than or equal to 7.2. The 7.3 release was the first
with multibyte support compiled by default and the driver uses
its character set translation facilities instead of trying to do
it itself.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>allowEncodingChanges</varname> = <type>boolean</type></term>
<listitem>
<para>
When using the V3 protocol the driver monitors changes in certain
server configuration parameters that should not be touched by
end users. The <literal>client_encoding</literal> setting is set
by the driver and should not be altered. If the driver detects
a change it will abort the connection. There is one legitimate
exception to this behavior though, using the <literal>COPY</literal>
command on a file residing on the server's filesystem. The only
means of specifying the encoding of this file is by altering the
<literal>client_encoding</literal> setting. The
<acronym>JDBC</acronym> team considers this a failing of the
<literal>COPY</literal> command and hopes to provide an alternate
means of specifying the encoding in the future, but for now there
is this <acronym>URL</acronym> parameter. Enable this only if
you need to override the client encoding when doing a copy.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>logUnclosedConnections</varname> = <type>boolean</type></term>
<listitem>
<para>
Clients may leak <classname>Connection</classname> objects by
failing to call its <function>close()</function> method.
Eventually these objects will be garbage collected and the
<function>finalize()</function> method will be called which will
close the <classname>Connection</classname> if caller has
neglected to do this himself. The usage of a finalizer is just
a stopgap solution. To help developers detect and correct the
source of these leaks the <literal>logUnclosedConnections</literal>
<acronym>URL</acronym> parameter has been added. It captures
a stacktrace at each <classname>Connection</classname> opening
and if the <function>finalize()</function> method is reached without
having been closed the stacktrace is printed to the log.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>binaryTransfer</varname> = <type>boolean</type></term>
<listitem>
<para>
The postgresql protocol v3 supports both binary and text transfer
of fields. When binaryTransfer is enabled the driver
requests binary transfer for all supported types. Using the binary
transfer is more optimal for both the server and the client.
Previously driver versions supported only text transfers. The old
functionality can be obtained by setting this field to false.
Currently the following column types currently support binary encoding:
<literal>BYTEA</literal>, <literal>TIMEx</literal>,
<literal>TIMESTAMP*</literal>, <literal>DATE</literal>,
<literal>INT*</literal> and <literal>FLOAT*</literal>.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>prepareThreshold</varname> = <type>int</type></term>
<listitem>
<para>
Determine the number of <classname>PreparedStatement</classname>
executions required before switching over to use server side prepared
statements. The default is five, meaning start using server side
prepared statements on the fifth execution of the same
<classname>PreparedStatement</classname> object. More
information on server side prepared
statements is available in <xref linkend="server-prepare" />.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>loginTimeout</varname> = <type>int</type></term>
<listitem>
<para>
Specify how long to wait for establishment of a database connection.
The timeout is specified in seconds.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>socketTimeout</varname> = <type>int</type></term>
<listitem>
<para>
The timeout value used for socket read operations. If reading
from the server takes longer than this value, the connection is
closed. This can be used as both a brute force global query
timeout and a method of detecting network problems. The timeout
is specified in seconds and a value of zero means that it is disabled.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>tcpKeepAlive</varname> = <type>boolean</type></term>
<listitem>
<para>
Enable or disable TCP keep-alive probe. The default is
<literal>false</literal>.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>unknownLength</varname> = <type>int</type></term>
<listitem>
<para>
Certain postgresql types such as <type>text</type> do not
have a well defined length. When returning meta-data about
these types through functions like
<function>ResultSetMetaData.getColumnDisplaySize</function>
and <function>ResultSetMetaData.getPrecision</function>
we must provide a value and various client tools have
different ideas about what they would like to see. This
parameter specifies the length to return for types of
unknown length.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>stringtype</varname> = <type>String</type></term>
<listitem>
<para>
Specify the type to use when binding <classname>PreparedStatement</classname> parameters
set via <function>setString()</function>. If <varname>stringtype</varname> is set to
<literal>varchar</literal> (the default), such parameters will be sent to the server as
<type>varchar</type> parameters. If <varname>stringtype</varname> is set to
<literal>unspecified</literal>, parameters will be sent to the server as untyped values,
and the server will attempt to infer an appropriate type. This is useful if you have an
existing application that uses <function>setString()</function> to set parameters that
are actually some other type, such as integers, and you are unable to change the
application to use an appropriate method such as <function>setInt()</function>.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>kerberosServerName</varname> = <type>String</type></term>
<listitem>
<para>
The Kerberos service name to use when authenticating with GSSAPI. This is
equivalent to libpq's PGKRBSRVNAME environment variable and defaults to
"postgres".
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>jaasApplicationName</varname> = <type>String</type></term>
<listitem>
<para>
Specifies the name of the <acronym>JAAS</acronym> system or application
login configuration.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>ApplicationName</varname> = <type>String</type></term>
<listitem>
<para>
Specifies the name of the application that is using the connection.
This allows a database administrator to see what applications are
connected to the server and what resources they are using through
views like pg_stat_activity.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>sendBufferSize</varname> = <type>int</type></term>
<listitem>
<para>
Sets SO_SNDBUF on the connection stream
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><varname>recvBufferSize</varname> = <type>int</type></term>
<listitem>
<para>
Sets SO_RCVBUF on the connection stream
</para>
</listitem>
</varlistentry>
</variablelist>
</para>
</sect2>
</sect1>
</chapter>
<chapter id="ssl">
<title>Using <acronym>SSL</acronym></title>
<sect1 id="ssl-server">
<title>Configuring the Server</title>
<para>
Configuring the <productname>PostgreSQL</productname> server for
<acronym>SSL</acronym> is covered in the
<ulink url="http://www.postgresql.org/docs/current/static/ssl-tcp.html">main documentation</ulink>,
so it will not be repeated here. Before trying to access your
<acronym>SSL</acronym> enabled server from Java, make sure you
can get to it via <command>psql</command>. You should see output
like the following if you have established a <acronym>SSL</acronym>
connnection.
</para>
<programlisting>
$ ./bin/psql -h localhost
Welcome to psql 8.0.0rc5, the PostgreSQL interactive terminal.
Type: \copyright for distribution terms
\h for help with SQL commands
\? for help with psql commands
\g or terminate with semicolon to execute query
\q to quit
SSL connection (cipher: DHE-RSA-AES256-SHA, bits: 256)
jurka=#
</programlisting>
</sect1>
<sect1 id="ssl-client">
<title>Configuring the Client</title>
<para>
If <acronym>SSL</acronym> is initiated by setting the <literal>ssl</literal>
connection parameter, then unlike <application>psql</application> and other
<application>libpq</application> based programs the
<acronym>JDBC</acronym> driver does server certificate
validation by default. This means that when establishing a
<acronym>SSL</acronym> connection the <acronym>JDBC</acronym>
driver will validate the server's identity preventing
"man in the middle" attacks. It does this by checking that
the server certificate is signed by a trusted authority. If
you have a certificate signed by a global certificate authority
(<acronym>CA</acronym>), there is nothing further to do
because Java comes with copies of the most common CA's certificates.
If you are dealing with a self-signed certificate though, you
need to make this available to the Java client to enable it
to validate the server's certificate.
<note>
<para>
Only the <acronym>JDBC</acronym> 3 driver supports
<acronym>SSL</acronym>. The 1.4 <acronym>JDK</acronym>
was the first version to come bundled with <acronym>SSL</acronym>
support. Previous <acronym>JDK</acronym> versions that wanted
to use <acronym>SSL</acronym> could make use of the additional
<acronym>JSSE</acronym> library, but it does not support the
full range of features utilized by the
<productname>PostgreSQL</productname> <acronym>JDBC</acronym>
driver.
</para>
</note>
</para>
<para>
To make the server certificate available to Java, the first step
is to convert it to a form Java understands.
<programlisting>
openssl x509 -in server.crt -out server.crt.der -outform der
</programlisting>
From here the easiest thing to do is import this certificate into Java's
system truststore.
<programlisting>
keytool -keystore $JAVA_HOME/lib/security/cacerts -alias postgresql -import -file server.crt.der
</programlisting>
The default password for the cacerts keystore is <literal>changeit</literal>. The alias to postgesql is not important and you may select any name you desire.
</para>
<para>
If you do not have access to the system cacerts truststore you can create your own truststore.
<programlisting>
keytool -keystore mystore -alias postgresql -import -file server.crt.der
</programlisting>
When starting your Java application you must specify this keystore and
password to use.
<programlisting>
java -Djavax.net.ssl.trustStore=mystore -Djavax.net.ssl.trustStorePassword=mypassword com.mycompany.MyApp
</programlisting>
In the event of problems extra debugging information is available
by adding <literal>-Djavax.net.debug=ssl</literal> to your command
line.
</para>
<para>
To instruct the <acronym>JDBC</acronym> driver to try and establish
a <acronym>SSL</acronym> connection you must add the connection
<acronym>URL</acronym> parameter <literal>ssl=true</literal>.
</para>
<sect2 id="nonvalidating">
<title>Using SSL without Certificate Validation</title>
<para>
In some situations it may not be possible to configure your Java
environment to make the server certificate available, for example
in an applet. For a large scale deployment it would be best to
get a certificate signed by recognized certificate authority, but
that is not always an option. The <acronym>JDBC</acronym> driver
provides an option to establish a <acronym>SSL</acronym> connection
without doing any validation, but please understand the risk
involved before enabling this option.
</para>
<para>
A non-validating connection is established via a custom
<classname>SSLSocketFactory</classname> class that is provided with
the driver. Setting the connection <acronym>URL</acronym>
parameter
<literal>sslfactory=org.postgresql.ssl.NonValidatingFactory</literal>
will turn off all <acronym>SSL</acronym> validation.
</para>
</sect2>
</sect1>
<sect1 id="ssl-factory">
<title>Custom SSLSocketFactory</title>
<para>
<productname>PostgreSQL</productname> provides a way for developers
to customize how a <acronym>SSL</acronym> connection is established.
This may be used to provide a custom certificate source or other
extensions by allowing the developer to create their own
<classname>SSLContext</classname> instance. The connection
<acronym>URL</acronym> parameters
<literal>sslfactory</literal> and <literal>sslfactoryarg</literal>
allow the user to specify which custom class to use for creating
the <classname>SSLSocketFactory</classname>. The class name specified
by <literal>sslfactory</literal> must extend
<classname>javax.net.ssl.SSLSocketFactory</classname> and be available
to the driver's classloader. This class
must have a zero argument constructor or a single argument
constructor taking a <type>Properies</type> argument where the connection
properties are passed or a single argument constructor taking a
<type>String</type> argument. This argument
may optionally be supplied by <literal>sslfactoryarg</literal>.
</para>
<para>
The sslfactory must not initiate a handshake in it's
createSocket method, because a second startHandsake invocation
in the <acronym>JDBC</acronym> driver will break the connection.
If an <literal>sslhostnameverifier</literal> class is supplied,
it is still responsible for handling the hostname verification.
</para>
<para>
Information on how to actually implement such a class is beyond
the scope of this documentation. Places to look for help are the
<ulink url="http://docs.oracle.com/javase/1.5.0/docs/guide/security/jsse/JSSERefGuide.html">
<acronym>JSSE</acronym> Reference Guide</ulink> and the source to the
<classname>NonValidatingFactory</classname> provided by the
<acronym>JDBC</acronym> driver.
</para>
<para>
The Java <acronym>SSL</acronym> <acronym>API</acronym> is not very
well known to the <acronym>JDBC</acronym> driver developers and we
would be interested in any interesting and generally useful
extensions that you have implemented using this mechanism.
Specifically it would be nice to be able to provide client certificates
to be validated by the server.
</para>
</sect1>
</chapter>
<chapter id="query">
<title>Issuing a Query and Processing the Result</title>
<indexterm zone="query">
<primary>Statement</primary>
</indexterm>
<indexterm zone="query">
<primary>PreparedStatement</primary>
</indexterm>
<indexterm zone="query">
<primary>ResultSet</primary>
</indexterm>
<para>
Any time you want to issue <acronym>SQL</acronym> statements to
the database, you require a <classname>Statement</classname> or
<classname>PreparedStatement</classname> instance. Once you have
a <classname>Statement</classname> or
<classname>PreparedStatement</classname>, you can use issue a
query. This will return a <classname>ResultSet</classname>
instance, which contains the entire result (see <xref linkend="query-with-cursor"/>
here for how to alter this behaviour).
<xref linkend="query-example"/> illustrates this process.
</para>
<example id="query-example">
<title>Processing a Simple Query in <acronym>JDBC</acronym></title>
<para>
This example will issue a simple query and print out the first
column of each row using a <classname>Statement</classname>.
<programlisting>
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM mytable WHERE columnfoo = 500");
while (rs.next()) {
System.out.print("Column 1 returned ");
System.out.println(rs.getString(1));
}
rs.close();
st.close();
</programlisting>
</para>
<para>
This example issues the same query as before but uses
a <classname>PreparedStatement</classname>
and a bind value in the query.
<programlisting>
int foovalue = 500;
PreparedStatement st = conn.prepareStatement("SELECT * FROM mytable WHERE columnfoo = ?");
st.setInt(1, foovalue);
ResultSet rs = st.executeQuery();
while (rs.next()) {
System.out.print("Column 1 returned ");
System.out.println(rs.getString(1));
}
rs.close();
st.close();
</programlisting>
</para>
</example>
<sect1 id="query-with-cursor">
<title>Getting results based on a cursor</title>
<para>By default the driver collects all the results for the
query at once. This can be inconvenient for large data sets so
the <acronym>JDBC</acronym> driver provides a means of basing
a <classname>ResultSet</classname> on a database cursor and
only fetching a small number of rows.</para>
<para>A small number of rows are cached on the
client side of the connection and when exhausted the next
block of rows is retrieved by repositioning the cursor.
</para>
<note>
<para>
Cursor based <classname>ResultSets</classname> cannot be used in all
situations. There a number of restrictions which will make the driver
silently fall back to fetching the whole <classname>ResultSet</classname>
at once.
<itemizedlist>
<listitem>
<para>
The connection to the server must be using the V3 protocol. This is the
default for (and is only supported by) server versions 7.4 and later.
</para>
</listitem>
<listitem>
<para>
The <classname>Connection</classname> must not be in autocommit
mode. The backend closes cursors at the end of transactions, so in
autocommit mode the backend will have closed the cursor before anything
can be fetched from it.
</para>
</listitem>
<listitem>
<para>
The <classname>Statement</classname> must be created with
a <classname>ResultSet</classname> type of
<literal>ResultSet.TYPE_FORWARD_ONLY</literal>.
This is the default, so no code will need to be rewritten to take
advantage of this, but it also means that you cannot scroll
backwards or otherwise jump around in the
<classname>ResultSet</classname>.
</para>
</listitem>
<listitem>
<para>
The query given must be a single statement, not multiple statements
strung together with semicolons.
</para>
</listitem>
</itemizedlist>
</para>
</note>
<example id="fetchsize-example">
<title>Setting fetch size to turn cursors on and off.</title>
<para>Changing code to cursor mode is as simple as setting the
fetch size of the <classname>Statement</classname> to the
appropriate size. Setting the fetch size back to 0 will cause
all rows to be cached (the default behaviour).
<programlisting>
// make sure autocommit is off
conn.setAutoCommit(false);
Statement st = conn.createStatement();
// Turn use of the cursor on.
st.setFetchSize(50);
ResultSet rs = st.executeQuery("SELECT * FROM mytable");
while (rs.next()) {
System.out.print("a row was returned.");
}
rs.close();
// Turn the cursor off.
st.setFetchSize(0);
rs = st.executeQuery("SELECT * FROM mytable");
while (rs.next()) {
System.out.print("many rows were returned.");
}
rs.close();
// Close the statement.
st.close();
</programlisting>
</para>
</example>
</sect1>
<sect1 id="statement">
<title>Using the <classname>Statement</classname> or <classname>PreparedStatement</classname> Interface</title>
<para>
The following must be considered when using the
<classname>Statement</classname> or
<classname>PreparedStatement</classname> interface:
<itemizedlist>
<listitem>
<para>
You can use a single <classname>Statement</classname> instance
as many times as you want. You could create one as soon as you
open the connection and use it for the connection's
lifetime. But you have to remember that only one
<classname>ResultSet</classname> can exist per
<classname>Statement</classname> or
<classname>PreparedStatement</classname> at a given time.
</para>
</listitem>
<listitem>
<para>
If you need to perform a query while processing a
<classname>ResultSet</classname>, you can simply create and
use another <classname>Statement</classname>.
</para>
</listitem>
<listitem>
<para>
If you are using threads, and several are using the database,
you must use a separate <classname>Statement</classname> for
each thread. Refer to <xref linkend="thread"/> if you are
thinking of using threads, as it covers some important points.
</para>
</listitem>
<listitem>
<para>
When you are done using the <classname>Statement</classname>
or <classname>PreparedStatement</classname>
you should close it.
</para>
</listitem>
</itemizedlist>
</para>
</sect1>
<sect1 id="resultset">
<title>Using the <classname>ResultSet</classname> Interface</title>
<para>
The following must be considered when using the
<classname>ResultSet</classname> 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>
You must close a <classname>ResultSet</classname> by calling
<function>close()</function> once you have finished using it.
</para>
</listitem>
<listitem>
<para>
Once you make another query with the
<classname>Statement</classname> used to create a
<classname>ResultSet</classname>, the currently open
<classname>ResultSet</classname> instance is closed
automatically.
</para>
</listitem>
</itemizedlist>
</para>
</sect1>
<sect1 id="update">
<title>Performing Updates</title>
<para>
To change data (perform an <literal>INSERT</literal>,
<literal>UPDATE</literal>, or <literal>DELETE</literal>) you use
the <function>executeUpdate()</function> method. This method is
similar to the method <function>executeQuery()</function> used to
issue a <literal>SELECT</literal> statement, but it doesn't return
a <classname>ResultSet</classname>; instead it returns the number
of rows affected by the <literal>INSERT</literal>,
<literal>UPDATE</literal>, or <literal>DELETE</literal> statement.
<xref linkend="delete-example"/> illustrates the usage.
</para>
<example id="delete-example">
<title>Deleting Rows in <acronym>JDBC</acronym></title>
<para>
This example will issue a simple <literal>DELETE</literal>
statement and print out the number of rows deleted.
<programlisting>
int foovalue = 500;
PreparedStatement st = conn.prepareStatement("DELETE FROM mytable WHERE columnfoo = ?");
st.setInt(1, foovalue);
int rowsDeleted = st.executeUpdate();
System.out.println(rowsDeleted + " rows deleted");
st.close();
</programlisting>
</para>
</example>
</sect1>
<sect1 id="ddl">
<title>Creating and Modifying Database Objects</title>
<para>
To create, modify or drop a database object like a table or view
you use the <function>execute()</function> method. This method is
similar to the method <function>executeQuery()</function>, but it
doesn't return a result. <xref linkend="drop-table-example"/>
illustrates the usage.
</para>
<example id="drop-table-example">
<title>Dropping a Table in <acronym>JDBC</acronym></title>
<para>
This example will drop a table.
<programlisting>
Statement st = conn.createStatement();
st.execute("DROP TABLE mytable");
st.close();
</programlisting>
</para>
</example>
</sect1>
</chapter>
<chapter id="callproc">
<title>Calling Stored Functions</title>
<example id="call-function-example">
<title>Calling a built in stored function</title>
<para>This example shows how to call
a <productname>PostgreSQL</productname> built in
function, <function>upper</function>, which simply converts the
supplied string argument to uppercase.
<programlisting>
CallableStatement upperProc = conn.prepareCall("{ ? = call upper( ? ) }");
upperProc.registerOutParameter(1, Types.VARCHAR);
upperProc.setString(2, "lowercase to uppercase");
upperProc.execute();
String upperCased = upperProc.getString(1);
upperProc.close();
</programlisting>
</para>
</example>
<sect1 id="callproc-resultset">
<title>Obtaining a <classname>ResultSet</classname> from a stored function</title>
<para><productname>PostgreSQL's</productname> stored functions
can return results in two different ways. The function may return
either a <type>refcursor</type> value or a <literal>SETOF</literal>
some datatype. Depending on which of these return methods are used
determines how the function should be called.
</para>
<sect2 id="callproc-resultset-setof">
<title>From a Function Returing <literal>SETOF</literal> type</title>
<para>
Functions that return data as a set should not be called via the
<classname>CallableStatement</classname> interface, but instead should
use the normal <classname>Statement</classname> or
<classname>PreparedStatement</classname> interfaces.
</para>
<example id="setof-resultset">
<title>
Getting <literal>SETOF</literal> type values from a function
</title>
<programlisting>
Statement stmt = conn.createStatement();
stmt.execute("CREATE OR REPLACE FUNCTION setoffunc() RETURNS SETOF int AS "
+ "' SELECT 1 UNION SELECT 2;' LANGUAGE sql");
ResultSet rs = stmt.executeQuery("SELECT * FROM setoffunc()");
while (rs.next()) {
// do something
}
rs.close();
stmt.close();
</programlisting>
</example>
</sect2>
<sect2 id="callproc-resultset-refcursor">
<title>From a Function Returing a <type>refcursor</type></title>
<para>
When calling a function that returns
a <type>refcursor</type> you must cast the return type
of <function>getObject</function> to
a <classname>ResultSet</classname>
<note>
<para>
One notable limitation of the current support for a
<classname>ResultSet</classname> created from a
<type>refcursor</type> is that even though it is a cursor
backed <classname>ResultSet</classname>, all data will be retrieved
and cached on the client. The <classname>Statement</classname>
fetch size parameter described in
<xref linkend="query-with-cursor" /> is ignored. This limitation
is a deficiency of the <acronym>JDBC</acronym> driver,
not the server, and it is technically possible to remove it,
we just haven't found the time.
</para>
</note>
</para>
<example id="get-refcursor-from-function-call">
<title>
Getting <type>refcursor</type> Value From a Function
</title>
<programlisting>
// Setup function to call.
Statement stmt = conn.createStatement();
stmt.execute("CREATE OR REPLACE FUNCTION refcursorfunc() RETURNS refcursor AS '"
+ " DECLARE "
+ " mycurs refcursor; "
+ " BEGIN "
+ " OPEN mycurs FOR SELECT 1 UNION SELECT 2; "
+ " RETURN mycurs; "
+ " END;' language plpgsql");
stmt.close();
// We must be inside a transaction for cursors to work.
conn.setAutoCommit(false);
// Procedure call.
CallableStatement proc = conn.prepareCall("{ ? = call refcursorfunc() }");
proc.registerOutParameter(1, Types.OTHER);
proc.execute();
ResultSet results = (ResultSet) proc.getObject(1);
while (results.next()) {
// do something with the results...
}
results.close();
proc.close();
</programlisting>
</example>
<para>It is also possible to treat the <type>refcursor</type>
return value as a cursor name directly. To do this, use the
<function>getString</function> of <classname>ResultSet</classname>.
With the underlying cursor name, you are free to directly use cursor
commands on it, such as <literal>FETCH</literal> and
<literal>MOVE</literal>.
</para>
<example id="refcursor-string-example">
<title>Treating <type>refcursor</type> as a cursor name</title>
<programlisting>
conn.setAutoCommit(false);
CallableStatement proc = conn.prepareCall("{ ? = call refcursorfunc() }");
proc.registerOutParameter(1, Types.OTHER);
proc.execute();
String cursorName = proc.getString(1);
proc.close();
</programlisting>
</example>
</sect2>
</sect1>
</chapter>
<chapter id="binary-data">
<title>Storing Binary Data</title>
<indexterm zone="binary-data">
<primary>bytea</primary>
<secondary sortas="JDBC">in JDBC</secondary>
</indexterm>
<indexterm zone="binary-data">
<primary>large object</primary>
<secondary sortas="JDBC">in JDBC</secondary>
</indexterm>
<para>
<productname>PostgreSQL</productname> provides two distinct ways to
store binary data. Binary data can be stored in a table using
the data type <type>bytea</type> or by using the Large Object
feature which stores the binary data in a separate table in a special
format and refers to that table by storing a value of type
<type>oid</type> in your table.
</para>
<para>
In order to determine which method is appropriate you
need to understand the limitations of each method. The
<type>bytea</type> data type is not well suited for storing very
large amounts of binary data. While a column of type
<type>bytea</type> can hold up to 1 GB of binary data, it would
require a huge amount of memory to
process such a large value. The Large Object method for
storing binary data is better suited to storing very large values,
but it has its own limitations. Specifically deleting a row
that contains a Large Object reference does not delete the Large Object.
Deleting the Large Object is a separate operation that needs to
be performed. Large Objects also have some security
issues since anyone connected to the database can view
and/or modify any Large Object, even if they don't have
permissions to view/update the row containing the Large Object reference.
</para>
<para>
Version 7.2 was the first release of the <acronym>JDBC</acronym> driver
that supports the <type>bytea</type> data type. The introduction of
this functionality in 7.2 has introduced a change in behavior
as compared to previous releases. Since 7.2, the methods
<function>getBytes()</function>, <function>setBytes()</function>,
<function>getBinaryStream()</function>, and
<function>setBinaryStream()</function> operate on
the <type>bytea</type> data type. In 7.1 and earlier, these methods operated
on the <type>oid</type> data type associated with Large Objects.
It is possible to revert the driver back to the old 7.1 behavior
by setting the property <literal>compatible</literal> on
the <classname>Connection</classname> object to the value
<literal>7.1</literal>. More details on connection properties are
available in <xref linkend="connection-parameters" />.
</para>
<para>
To use the <type>bytea</type> data type you should simply use
the <function>getBytes()</function>, <function>setBytes()</function>,
<function>getBinaryStream()</function>, or
<function>setBinaryStream()</function> methods.
</para>
<para>
To use the Large Object functionality you can use either the
<classname>LargeObject</classname> class provided by the
<productname>PostgreSQL</productname> <acronym>JDBC</acronym> driver, or by
using the <function>getBLOB()</function> and
<function>setBLOB()</function> methods.
</para>
<important>
<para>
You must access Large Objects within an <acronym>SQL</acronym>
transaction block. You can start a transaction block by calling
<function>setAutoCommit(false)</function>.
</para>
</important>
<para>
<xref linkend="binary-data-example"/> contains some examples on
how to process binary data using the <productname>PostgreSQL</productname>
<acronym>JDBC</acronym> driver.
</para>
<example id="binary-data-example">
<title>Processing Binary Data in <acronym>JDBC</acronym></title>
<para>
For example, suppose you have a table containing the file names of
images and you also want to store the image in a <type>bytea</type>
column:
<programlisting>
CREATE TABLE images (imgname text, img bytea);
</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, (int)file.length());
ps.executeUpdate();
ps.close();
fis.close();
</programlisting>
Here, <function>setBinaryStream()</function> transfers a set number
of bytes from a stream into the column of type <type>bytea</type>.
This also could have been done using the <function>setBytes()</function>
method if the contents of the image was already in a
<classname>byte[]</classname>.
<note>
<para>
The length parameter to <function>setBinaryStream</function> must be
correct. There is no way to indicate that the stream is of unknown
length. If you are in this situation, you must read the stream yourself
into temporary storage and determine the length. Now with the correct
length you may send the data from temporary storage on to the driver.
</para>
</note>
</para>
<para>
Retrieving an image is even easier. (We use
<classname>PreparedStatement</classname> here, but the
<classname>Statement</classname> class can equally be used.)
<programlisting>
PreparedStatement ps = conn.prepareStatement("SELECT img FROM images WHERE imgname = ?");
ps.setString(1, "myimage.gif");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
byte[] imgBytes = rs.getBytes(1);
// use the data in some way here
}
rs.close();
ps.close();
</programlisting>
</para>
<para>
Here the binary data was retrieved as an
<classname>byte[]</classname>. You could have used a
<classname>InputStream</classname> object instead.
</para>
<para>
Alternatively you could be storing a very large file and want to use
the <classname>LargeObject</classname> <acronym>API</acronym> to
store the file:
<programlisting>
CREATE TABLE imageslo (imgname text, imgoid oid);
</programlisting>
</para>
<para>
To insert an image, you would use:
<programlisting>
// All LargeObject API calls must be within a transaction block
conn.setAutoCommit(false);
// Get the Large Object Manager to perform operations with
LargeObjectManager lobj = ((org.postgresql.PGConnection)conn).getLargeObjectAPI();
// Create a new large object
long oid = lobj.createLO(LargeObjectManager.READ | LargeObjectManager.WRITE);
// Open the large object for writing
LargeObject obj = lobj.open(oid, LargeObjectManager.WRITE);
// Now open the file
File file = new File("myimage.gif");
FileInputStream fis = new FileInputStream(file);
// Copy the data from the file to the large object
byte buf[] = new byte[2048];
int s, tl = 0;
while ((s = fis.read(buf, 0, 2048)) > 0) {
obj.write(buf, 0, s);
tl += s;
}
// Close the large object
obj.close();
// Now insert the row into imageslo
PreparedStatement ps = conn.prepareStatement("INSERT INTO imageslo VALUES (?, ?)");
ps.setString(1, file.getName());
ps.setLong(2, oid);
ps.executeUpdate();
ps.close();
fis.close();
// Finally, commit the transaction.
conn.commit();
</programlisting>
</para>
<para>
Retrieving the image from the Large Object:
<programlisting>
// All LargeObject API calls must be within a transaction block
conn.setAutoCommit(false);
// Get the Large Object Manager to perform operations with
LargeObjectManager lobj = ((org.postgresql.PGConnection)conn).getLargeObjectAPI();
PreparedStatement ps = conn.prepareStatement("SELECT imgoid FROM imageslo WHERE imgname = ?");
ps.setString(1, "myimage.gif");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
// Open the large object for reading
long oid = rs.getLong(1);
LargeObject obj = lobj.open(oid, LargeObjectManager.READ);
// Read the data
byte buf[] = new byte[obj.size()];
obj.read(buf, 0, obj.size());
// Do something with the data read here
// Close the object
obj.close();
}
rs.close();
ps.close();
// Finally, commit the transaction.
conn.commit();
</programlisting>
</para>
</example>
</chapter>
<chapter id="escapes">
<title><acronym>JDBC</acronym> escapes</title>
<para>
The <acronym>JDBC</acronym> specification (like the <acronym>ODBC</acronym>
specification) acknowledges the fact that some vendor specific
<acronym>SQL</acronym> may be required for certain <acronym>RDBMS</acronym>
features. To aid developers in writing portable <acronym>JDBC</acronym>
applications across multiple database products, a special escape syntax is
used to specify the generic commands the developer wants to be run. The
<acronym>JDBC</acronym> driver translates these escape sequences into
native syntax for its specific database.
For more information consult the section 4.1.5 from the
<ulink url="http://docs.oracle.com/javase/1.5.0/docs/guide/jdbc/getstart/statement.html#17215"><acronym>JDBC</acronym> Technology Guide</ulink>
(bundled with the <productname>Oracle</productname> <acronym>JRE</acronym>
documentation) and the section 13.4 from the
<ulink url="http://www.oracle.com/technetwork/java/download-141179.html#corespec40"><acronym>JDBC</acronym> 4.0 specification</ulink>.
</para>
<para>
The parsing of the sql statements for these escapes can be disabled using <literal>Statement.setEscapeProcessing(false)</literal>.
</para>
<para>
<literal>Connection.nativeSQL(String sql)</literal> provides another way to have escapes processed.
It translates the given <acronym>SQL</acronym> to a <acronym>SQL</acronym> suitable for the <productname>PostgreSQL</productname> backend.
</para>
<example id="escape-use-example">
<title>Using jdbc escapes</title>
<para>
To use the <acronym>JDBC</acronym> escapes, you simply write your <acronym>SQL</acronym> replacing date/time literal
values, outer join and functions by the <acronym>JDBC</acronym> escape syntax.
For example :
<programlisting>
ResultSet rs = st.executeQuery("SELECT {fn week({d '2005-01-24'})}");
</programlisting>
is the portable version for
<programlisting>
ResultSet rs = st.executeQuery("SELECT extract(week from DATE '2005-01-24')");
</programlisting>
</para>
</example>
<sect1 id="like-escape">
<title>Escape for like escape character</title>
<para>
You can specify which escape character to use in strings comparison (with <literal>LIKE</literal>) to protect wildcards
characters ('%' and '_') by adding the following escape : <literal>{escape 'escape-character'}</literal>.
The driver supports this only at the end of the comparison expression.
</para>
<para>
For example, you can compare string values using '|' as escape character to protect '_' :
<programlisting>
rs = stmt.executeQuery("select str2 from comparisontest where str1 like '|_abcd' {escape '|'} ");
</programlisting>
</para>
</sect1>
<sect1 id="outer-joins-escape">
<title>Escape for outer joins</title>
<para>
You can specify outer joins using the following syntax:
<literal>{oj table (LEFT|RIGHT|FULL) OUTER JOIN (table | outer-join)
ON search-condition }</literal>
</para>
<para>
For example :
<programlisting>
rs = stmt.executeQuery( "select * from {oj a left outer join b on (a.i=b.i)} ");
</programlisting>
</para>
</sect1>
<sect1 id="escapes-datetime">
<title>Date-time escapes</title>
<para>
The <acronym>JDBC</acronym> specification defines escapes for specifying date, time and timestamp values which are supported by the
driver.
</para>
<variablelist>
<varlistentry>
<term>date</term>
<listitem>
<para>
<literal>{d 'yyyy-mm-dd'}</literal> which is translated to <literal>DATE 'yyyy-mm-dd'</literal>
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>time</term>
<listitem>
<para><literal>{t 'hh:mm:ss'}</literal> which is translated to <literal>TIME 'hh:mm:ss'</literal></para>
</listitem>
</varlistentry>
<varlistentry>
<term>timestamp</term>
<listitem><para>
<literal>{ts 'yyyy-mm-dd hh:mm:ss.f...'}</literal> which is translated to <literal>TIMESTAMP 'yyyy-mm-dd hh:mm:ss.f'</literal>
The fractional seconds (.f...) portion of the TIMESTAMP can be omitted. </para>
</listitem>
</varlistentry>
</variablelist>
</sect1>
<sect1 id="escaped-functions">
<title>Escaped scalar functions</title>
<para>
The <acronym>JDBC</acronym> specification defines functions with an escape call syntax : <literal>{fn function_name(arguments)}</literal>.
The following tables show which functions are supported by the <productname>Postgres<acronym>SQL</acronym></productname> driver.
The driver supports the nesting and the mixing of escaped functions and escaped values.
The appendix C of the <acronym>JDBC</acronym> specification describes the functions.
</para>
<para>
Some functions in the following tables are translated but not reported as supported because they are
duplicating or changing ther order of the arguments. While this is harmless for literal values or
columns, it will cause problems when using prepared statements.
For example "<literal>{fn right(?,?)}</literal>" will be translated to "<literal>substring(? from (length(?)+1-?))</literal>".
As you can see the translated <acronym>SQL</acronym> requires more parameters than before the translation but the
driver will not automatically handle this.
</para>
<table id="escape-numeric-functions-table">
<title>Supported escaped numeric functions</title>
<tgroup cols="4">
<thead>
<row>
<entry>function</entry>
<entry>reported as supported</entry>
<entry>translation</entry>
<entry>comments</entry>
</row>
</thead>
<tbody>
<row>
<entry>abs(arg1)</entry>
<entry>yes</entry>
<entry>abs(arg1)</entry>
<entry></entry>
</row>
<row>
<entry>acos(arg1)</entry>
<entry>yes</entry>
<entry>acos(arg1)</entry>
<entry></entry>
</row>
<row>
<entry>asin(arg1)</entry>
<entry>yes</entry>
<entry>asin(arg1)</entry>
<entry></entry>
</row>
<row>
<entry>atan(arg1)</entry>
<entry>yes</entry>
<entry>atan(arg1)</entry>
<entry></entry>
</row>
<row>
<entry>atan2(arg1,arg2)</entry>
<entry>yes</entry>
<entry>atan2(arg1,arg2)</entry>
<entry></entry>
</row>
<row>
<entry>ceiling(arg1)</entry>
<entry>yes</entry>
<entry>ceil(arg1)</entry>
<entry></entry>
</row>
<row>
<entry>cos(arg1)</entry>
<entry>yes</entry>
<entry>cos(arg1)</entry>
<entry></entry>
</row>
<row>
<entry>cot(arg1)</entry>
<entry>yes</entry>
<entry>cot(arg1)</entry>
<entry></entry>
</row>
<row>
<entry>degrees(arg1)</entry>
<entry>yes</entry>
<entry>degrees(arg1)</entry>
<entry></entry>
</row>
<row>
<entry>exp(arg1)</entry>
<entry>yes</entry>
<entry>exp(arg1)</entry>
<entry></entry>
</row>
<row>
<entry>floor(arg1)</entry>
<entry>yes</entry>
<entry>floor(arg1)</entry>
<entry></entry>
</row>
<row>
<entry>log(arg1)</entry>
<entry>yes</entry>
<entry>ln(arg1)</entry>
<entry></entry>
</row>
<row>
<entry>log10(arg1)</entry>
<entry>yes</entry>
<entry>log(arg1)</entry>
<entry></entry>
</row>
<row>
<entry>mod(arg1,arg2)</entry>
<entry>yes</entry>
<entry>mod(arg1,arg2)</entry>
<entry></entry>
</row>
<row>
<entry>pi(arg1)</entry>
<entry>yes</entry>
<entry>pi(arg1)</entry>
<entry></entry>
</row>
<row>
<entry>power(arg1,arg2)</entry>
<entry>yes</entry>
<entry>pow(arg1,arg2)</entry>
<entry></entry>
</row>
<row>
<entry>radians(arg1)</entry>
<entry>yes</entry>
<entry>radians(arg1)</entry>
<entry></entry>
</row>
<row>
<entry>rand()</entry>
<entry>yes</entry>
<entry>random()</entry>
<entry></entry>
</row>
<row>
<entry>rand(arg1)</entry>
<entry>yes</entry>
<entry>setseed(arg1)*0+random()</entry>
<entry>The seed is initialized with the given argument and a new randow value is returned.</entry>
</row>
<row>
<entry>round(arg1,arg2)</entry>
<entry>yes</entry>
<entry>round(arg1,arg2)</entry>
<entry></entry>
</row>
<row>
<entry>sign(arg1)</entry>
<entry>yes</entry>
<entry>sign(arg1)</entry>
<entry></entry>
</row>
<row>
<entry>sin(arg1)</entry>
<entry>yes</entry>
<entry>sin(arg1)</entry>
<entry></entry>
</row>
<row>
<entry>sqrt(arg1)</entry>
<entry>yes</entry>
<entry>sqrt(arg1)</entry>
<entry></entry>
</row>
<row>
<entry>tan(arg1)</entry>
<entry>yes</entry>
<entry>tan(arg1)</entry>
<entry></entry>
</row>
<row>
<entry>truncate(arg1,arg2)</entry>
<entry>yes</entry>
<entry>trunc(arg1,arg2)</entry>
<entry></entry>
</row>
</tbody>
</tgroup>
</table>
<table id="escape-string-functions-table">
<title>Supported escaped string functions</title>
<tgroup cols="4">
<thead>
<row>
<entry>function</entry>
<entry>reported as supported</entry>
<entry>translation</entry>
<entry>comments</entry>
</row>
</thead>
<tbody>
<row>
<entry>ascii(arg1)</entry>
<entry>yes</entry>
<entry>ascii(arg1)</entry>
<entry></entry>
</row>
<row>
<entry>char(arg1)</entry>
<entry>yes</entry>
<entry>chr(arg1)</entry>
<entry></entry>
</row>
<row>
<entry>concat(arg1,arg2...)</entry>
<entry>yes</entry>
<entry>(arg1||arg2...)</entry>
<entry>The <acronym>JDBC</acronym> specification only require the two arguments version, but supporting more arguments was so easy...</entry>
</row>
<row>
<entry>insert(arg1,arg2,arg3,arg4)</entry>
<entry>no</entry>
<entry>overlay(arg1 placing arg4 from arg2 for arg3)</entry>
<entry>This function is not reported as supported since it changes the order of the arguments which can be a problem (for prepared statements by example).</entry>
</row>
<row>
<entry>lcase(arg1)</entry>
<entry>yes</entry>
<entry>lower(arg1)</entry>
<entry></entry>
</row>
<row>
<entry>left(arg1,arg2)</entry>
<entry>yes</entry>
<entry>substring(arg1 for arg2)</entry>
<entry></entry>
</row>
<row>
<entry>length(arg1)</entry>
<entry>yes</entry>
<entry>length(trim(trailing from arg1))</entry>
<entry></entry>
</row>
<row>
<entry>locate(arg1,arg2)</entry>
<entry>no</entry>
<entry>position(arg1 in arg2)</entry>
<entry></entry>
</row>
<row>
<entry>locate(arg1,arg2,arg3)</entry>
<entry>no</entry>
<entry>(arg2*sign(position(arg1 in substring(arg2 from arg3)+position(arg1 in substring(arg2 from arg3))</entry>
<entry>Not reported as supported since the three arguments version duplicate and change the order of the arguments.</entry>
</row>
<row>
<entry>ltrim(arg1)</entry>
<entry>yes</entry>
<entry>trim(leading from arg1)</entry>
<entry></entry>
</row>
<row>
<entry>repeat(arg1,arg2)</entry>
<entry>yes</entry>
<entry>repeat(arg1,arg2)</entry>
<entry></entry>
</row>
<row>
<entry>replace(arg1,arg2,arg3)</entry>
<entry>yes</entry>
<entry>replace(arg1,arg2,arg3)</entry>
<entry>Only reported as supported by 7.3 and above servers.</entry>
</row>
<row>
<entry>right(arg1,arg2)</entry>
<entry>no</entry>
<entry>substring(arg1 from (length(arg1)+1-arg2))</entry>
<entry>Not reported as supported since arg2 is duplicated.</entry>
</row>
<row>
<entry>rtrim(arg1)</entry>
<entry>yes</entry>
<entry>trim(trailing from arg1)</entry>
<entry></entry>
</row>
<row>
<entry>space(arg1)</entry>
<entry>yes</entry>
<entry>repeat(' ',arg1)</entry>
<entry></entry>
</row>
<row>
<entry>substring(arg1,arg2)</entry>
<entry>yes</entry>
<entry>substr(arg1,arg2)</entry>
<entry></entry>
</row>
<row>
<entry>substring(arg1,arg2,arg3)</entry>
<entry>yes</entry>
<entry>substr(arg1,arg2,arg3)</entry>
<entry></entry>
</row>
<row>
<entry>ucase(arg1)</entry>
<entry>yes</entry>
<entry>upper(arg1)</entry>
<entry></entry>
</row>
<row>
<entry>soundex(arg1)</entry>
<entry>no</entry>
<entry>soundex(arg1)</entry>
<entry>Not reported as supported since it requires the fuzzystrmatch contrib module.</entry>
</row>
<row>
<entry>difference(arg1,arg2)</entry>
<entry>no</entry>
<entry>difference(arg1,arg2)</entry>
<entry>Not reported as supported since it requires the fuzzystrmatch contrib module.</entry>
</row>
</tbody>
</tgroup>
</table>
<table id="escape-datetime-functions-table">
<title>Supported escaped date/time functions</title>
<tgroup cols="4">
<thead>
<row>
<entry>function</entry>
<entry>reported as supported</entry>
<entry>translation</entry>
<entry>comments</entry>
</row>
</thead>
<tbody>
<row>
<entry>curdate()</entry>
<entry>yes</entry>
<entry>current_date</entry>
<entry></entry>
</row>
<row>
<entry>curtime()</entry>
<entry>yes</entry>
<entry>current_time</entry>
<entry></entry>
</row>
<row>
<entry>dayname(arg1)</entry>
<entry>yes</entry>
<entry>to_char(arg1,'Day')</entry>
<entry></entry>
</row>
<row>
<entry>dayofmonth(arg1)</entry>
<entry>yes</entry>
<entry>extract(day from arg1)</entry>
<entry></entry>
</row>
<row>
<entry>dayofweek(arg1)</entry>
<entry>yes</entry>
<entry>extract(dow from arg1)+1</entry>
<entry>We must add 1 to be in the expected 1-7 range.</entry>
</row>
<row>
<entry>dayofyear(arg1)</entry>
<entry>yes</entry>
<entry>extract(doy from arg1)</entry>
<entry></entry>
</row>
<row>
<entry>hour(arg1)</entry>
<entry>yes</entry>
<entry>extract(hour from arg1)</entry>
<entry></entry>
</row>
<row>
<entry>minute(arg1)</entry>
<entry>yes</entry>
<entry>extract(minute from arg1)</entry>
<entry></entry>
</row>
<row>
<entry>month(arg1)</entry>
<entry>yes</entry>
<entry>extract(month from arg1)</entry>
<entry></entry>
</row>
<row>
<entry>monthname(arg1)</entry>
<entry>yes</entry>
<entry>to_char(arg1,'Month')</entry>
<entry></entry>
</row>
<row>
<entry>now()</entry>
<entry>yes</entry>
<entry>now()</entry>
<entry></entry>
</row>
<row>
<entry>quarter(arg1)</entry>
<entry>yes</entry>
<entry>extract(quarter from arg1)</entry>
<entry></entry>
</row>
<row>
<entry>second(arg1)</entry>
<entry>yes</entry>
<entry>extract(second from arg1)</entry>
<entry></entry>
</row>
<row>
<entry>week(arg1)</entry>
<entry>yes</entry>
<entry>extract(week from arg1)</entry>
<entry></entry>
</row>
<row>
<entry>year(arg1)</entry>
<entry>yes</entry>
<entry>extract(year from arg1)</entry>
<entry></entry>
</row>
<row>
<entry>timestampadd(argIntervalType,argCount,argTimeStamp)</entry>
<entry>yes</entry>
<entry>('(interval according to argIntervalType and argCount)'+argTimeStamp)</entry>
<entry>an argIntervalType value of <classname>SQL_TSI_FRAC_SECOND</classname> is not implemented since backend does not support it</entry>
</row>
<row>
<entry>timestampdiff(argIntervalType,argTimeStamp1,argTimeStamp2)</entry>
<entry>not</entry>
<entry>extract((interval according to argIntervalType) from argTimeStamp2-argTimeStamp1 )</entry>
<entry>only an argIntervalType value of <classname>SQL_TSI_FRAC_SECOND</classname>,<classname>SQL_TSI_FRAC_MINUTE</classname>,<classname>SQL_TSI_FRAC_HOUR</classname> or <classname>SQL_TSI_FRAC_DAY</classname> is supported </entry>
</row>
</tbody>
</tgroup>
</table>
<table id="escape-misc-functions-table">
<title>Supported escaped misc functions</title>
<tgroup cols="4">
<thead>
<row>
<entry>function</entry>
<entry>reported as supported</entry>
<entry>translation</entry>
<entry>comments</entry>
</row>
</thead>
<tbody>
<row>
<entry>database()</entry>
<entry>yes</entry>
<entry>current_database()</entry>
<entry>Only reported as supported by 7.3 and above servers.</entry>
</row>
<row>
<entry>ifnull(arg1,arg2)</entry>
<entry>yes</entry>
<entry>coalesce(arg1,arg2)</entry>
<entry></entry>
</row>
<row>
<entry>user()</entry>
<entry>yes</entry>
<entry>user</entry>
<entry></entry>
</row>
</tbody>
</tgroup>
</table>
</sect1>
</chapter>
<chapter id="ext">
<title><productname>PostgreSQL</productname> Extensions to the
<acronym>JDBC</acronym> <acronym>API</acronym></title>
<para>
<productname>PostgreSQL</productname> is an extensible database
system. You can add your own functions to the server, which can
then be called from queries, or even add your own data types. As
these are facilities unique to <productname>PostgreSQL</productname>,
we support them from Java, with a set of extension
<acronym>APIs</acronym>. Some features within the core of the
standard driver actually use these extensions to implement Large
Objects, etc.
</para>
<sect1 id="extensions">
<title>Accessing the Extensions</title>
<para>
To access some of the extensions, you need to use some extra
methods in the <classname>org.postgresql.PGConnection</classname>
class. In this case, you would need to case the return value of
<function>Driver.getConnection()</function>. For example:
<programlisting>
Connection db = Driver.getConnection(url, username, password);
// ...
// later on
Fastpath fp = ((org.postgresql.PGConnection)db).getFastpathAPI();
</programlisting>
</para>
</sect1>
<sect1 id="geometric">
<title>Geometric Data Types</title>
<para>
<productname>PostgreSQL</productname> has a set of data types that
can store geometric features into a table. These include single
points, lines, and polygons. We support these types in Java with
the org.postgresql.geometric package. Please consult the Javadoc
for the details of available classes and features metioned in
<xref linkend="reading" />.
</para>
<example id="geometric-circle-example">
<title>Using the circle datatype from <acronym>JDBC</acronym></title>
<programlisting>
import java.sql.*;
import org.postgresql.geometric.PGpoint;
import org.postgresql.geometric.PGcircle;
public class GeometricTest {
public static void main(String args[]) throws Exception {
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://localhost:5432/test";
Connection conn = DriverManager.getConnection(url,"test","");
Statement stmt = conn.createStatement();
stmt.execute("CREATE TEMP TABLE geomtest(mycirc circle)");
stmt.close();
insertCircle(conn);
retrieveCircle(conn);
conn.close();
}
private static void insertCircle(Connection conn) throws SQLException {
PGpoint center = new PGpoint(1, 2.5);
double radius = 4;
PGcircle circle = new PGcircle(center, radius);
PreparedStatement ps = conn.prepareStatement("INSERT INTO geomtest(mycirc) VALUES (?)");
ps.setObject(1, circle);
ps.executeUpdate();
ps.close();
}
private static void retrieveCircle(Connection conn) throws SQLException {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT mycirc, area(mycirc) FROM geomtest");
rs.next();
PGcircle circle = (PGcircle)rs.getObject(1);
double area = rs.getDouble(2);
PGpoint center = circle.center;
double radius = circle.radius;
System.out.println("Center (X, Y) = (" + center.x + ", " + center.y + ")");
System.out.println("Radius = " + radius);
System.out.println("Area = " + area);
}
}
</programlisting>
</example>
</sect1>
<sect1 id="largeobjects">
<title>Large Objects</title>
<para>
Large objects are supported in the standard
<acronym>JDBC</acronym> specification. However, that interface is
limited, and the <acronym>API</acronym> provided by <productname>PostgreSQL</productname> allows for random
access to the objects contents, as if it was a local file.
</para>
<para>
The org.postgresql.largeobject package provides to Java the <application>libpq</application>
C interface's large object <acronym>API</acronym>. It consists of
two classes, <classname>LargeObjectManager</classname>, which deals with creating,
opening and deleting large objects, and <classname>LargeObject</classname> which deals
with an individual object. For an example usage of this <acronym>API</acronym>,
please see <xref linkend="binary-data-example"/>.
</para>
</sect1>
<sect1 id="listennotify">
<title>Listen / Notify</title>
<para>
Listen and Notify provide a simple form of signal or interprocess
communication mechanism for a collection of processes accessing
the same <productname>PostgreSQL</productname> database. For more
information on notifications consult the main server documentation.
This section only deals with the <acronym>JDBC</acronym> specific
aspects of notifications.
</para>
<para>
Standard <literal>LISTEN</literal>, <literal>NOTIFY</literal>, and
<literal>UNLISTEN</literal> commands are issued via the
standard <classname>Statement</classname> interface. To retrieve
and process retrieved notifications the
<classname>Connection</classname> must be cast to the
<productname>PostgreSQL</productname> specific extension interface
<classname>PGConnection</classname>. From there the
<function>getNotifications()</function> method can be used to retrieve
any outstanding notifications.
</para>
<note>
<para>
A key limitation of the <acronym>JDBC</acronym> driver is that it
cannot receive asynchronous notifications and must poll the
backend to check if any notifications were issued.
</para>
</note>
<example id="listen-notify-example">
<title>Receiving Notifications</title>
<programlisting>
import java.sql.*;
public class NotificationTest {
public static void main(String args[]) throws Exception {
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://localhost:5432/test";
// Create two distinct connections, one for the notifier
// and another for the listener to show the communication
// works across connections although this example would
// work fine with just one connection.
Connection lConn = DriverManager.getConnection(url,"test","");
Connection nConn = DriverManager.getConnection(url,"test","");
// Create two threads, one to issue notifications and
// the other to receive them.
Listener listener = new Listener(lConn);
Notifier notifier = new Notifier(nConn);
listener.start();
notifier.start();
}
}
class Listener extends Thread {
private Connection conn;
private org.postgresql.PGConnection pgconn;
Listener(Connection conn) throws SQLException {
this.conn = conn;
this.pgconn = (org.postgresql.PGConnection)conn;
Statement stmt = conn.createStatement();
stmt.execute("LISTEN mymessage");
stmt.close();
}
public void run() {
while (true) {
try {
// issue a dummy query to contact the backend
// and receive any pending notifications.
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT 1");
rs.close();
stmt.close();
org.postgresql.PGNotification notifications[] = pgconn.getNotifications();
if (notifications != null) {
for (int i=0; i<notifications.length; i++) {
System.out.println("Got notification: " + notifications[i].getName());
}
}
// wait a while before checking again for new
// notifications
Thread.sleep(500);
} catch (SQLException sqle) {
sqle.printStackTrace();
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
}
class Notifier extends Thread {
private Connection conn;
public Notifier(Connection conn) {
this.conn = conn;
}
public void run() {
while (true) {
try {
Statement stmt = conn.createStatement();
stmt.execute("NOTIFY mymessage");
stmt.close();
Thread.sleep(2000);
} catch (SQLException sqle) {
sqle.printStackTrace();
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
}
</programlisting>
</example>
</sect1>
<sect1 id="server-prepare">
<title>Server Prepared Statements</title>
<para>
The <productname>PostgreSQL</productname> server allows clients
to compile sql statements that are expected to be reused to avoid the
overhead of parsing and planning the statement for every execution.
This functionality is available at the <acronym>SQL</acronym> level
via PREPARE and EXECUTE beginning with server version 7.3, and at the
protocol level beginning with server version 7.4, but as Java
developers we really just want to use the standard
<classname>PreparedStatement</classname> interface.
</para>
<note>
<para>
Previous versions of the driver used PREPARE and EXECUTE to
implement server-prepared statements. This is supported on all server
versions beginning with 7.3, but produced application-visible changes
in query results, such as missing ResultSet metadata and row update
counts. The current driver uses the V3 protocol-level equivalents which
avoid these changes in query results, but the V3 protocol is only
available beginning with server version 7.4. Enabling server-prepared
statements will have no affect when connected to a 7.3 server or when
explicitly using the V2 protocol to connect to a 7.4 server.
</para>
</note>
<para>
There are a number of ways to enable server side prepared statements
depending on your application's needs. The general method is to
set a threshold for a <classname>PreparedStatement</classname>.
An internal counter keeps track of how many times the statement has
been executed and when it reaches the threshold it will start to
use server side prepared statements.
</para>
<note>
<para>
Server side prepared statements are planned only once by the server.
This avoids the cost of replanning the query every time, but also
means that the planner cannot take advantage of the particular
parameter values used in a particular execution of the query.
You should be cautious about enabling the use of server side prepared
statements globally.
</para>
</note>
<example id="server-prepared-statement-example">
<title>Using server side prepared statements</title>
<programlisting>
import java.sql.*;
public class ServerSidePreparedStatement
{
public static void main(String args[]) throws Exception
{
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://localhost:5432/test";
Connection conn = DriverManager.getConnection(url,"test","");
PreparedStatement pstmt = conn.prepareStatement("SELECT ?");
// cast to the pg extension interface
org.postgresql.PGStatement pgstmt = (org.postgresql.PGStatement)pstmt;
// on the third execution start using server side statements
pgstmt.setPrepareThreshold(3);
for (int i=1; i<=5; i++)
{
pstmt.setInt(1,i);
boolean usingServerPrepare = pgstmt.isUseServerPrepare();
ResultSet rs = pstmt.executeQuery();
rs.next();
System.out.println("Execution: "+i+", Used server side: " + usingServerPrepare + ", Result: "+rs.getInt(1));
rs.close();
}
pstmt.close();
conn.close();
}
}
</programlisting>
<para>Which produces the expected result of using server side prepared statements upon the third execution.</para>
<programlisting>
Execution: 1, Used server side: false, Result: 1
Execution: 2, Used server side: false, Result: 2
Execution: 3, Used server side: true, Result: 3
Execution: 4, Used server side: true, Result: 4
Execution: 5, Used server side: true, Result: 5
</programlisting>
</example>
<para>
The example shown above requires the programmer to use
<productname>PostgreSQL</productname> specific code in a
supposedly portable API which is not ideal. Also it sets the
threshold only for that particular statement which is some extra
typing if we wanted to use that threshold for every statement.
Let's take a look at the other ways to set the threshold to enable
server side prepared statements. There is already a hierarchy in
place above a <classname>PreparedStatement</classname>, the
<classname>Connection</classname> it was created from, and above that
the source of the connection be it a <classname>Datasource</classname>
or a <acronym>URL</acronym>. The server side prepared statement
threshold can be set at any of these levels such that the value
will be the default for all of it's children.
</para>
<programlisting>
// pg extension interfaces
org.postgresql.PGConnection pgconn;
org.postgresql.PGStatement pgstmt;
// set a prepared statement threshold for connections created from this url
String url = "jdbc:postgresql://localhost:5432/test?prepareThreshold=3";
// see that the connection has picked up the correct threshold from the url
Connection conn = DriverManager.getConnection(url,"test","");
pgconn = (org.postgresql.PGConnection)conn;
System.out.println(pgconn.getPrepareThreshold()); // Should be 3
// see that the statement has picked up the correct threshold from the connection
PreparedStatement pstmt = conn.prepareStatement("SELECT ?");
pgstmt = (org.postgresql.PGStatement)pstmt;
System.out.println(pgstmt.getPrepareThreshold()); // Should be 3
// change the connection's threshold and ensure that new statements pick it up
pgconn.setPrepareThreshold(5);
PreparedStatement pstmt = conn.prepareStatement("SELECT ?");
pgstmt = (org.postgresql.PGStatement)pstmt;
System.out.println(pgstmt.getPrepareThreshold()); // Should be 5
</programlisting>
</sect1>
</chapter>
<chapter id="thread">
<title>Using the Driver in a Multithreaded or a Servlet Environment</title>
<indexterm zone="thread">
<primary>threads</primary>
<secondary sortas="JDBC">with JDBC</secondary>
</indexterm>
<para>
A problem with many <acronym>JDBC</acronym> drivers is that only
one thread can use a <classname>Connection</classname> at any one
time --- otherwise a thread could send a query while another one is
receiving results, and this could cause severe confusion.
</para>
<para>
The <productname>PostgreSQL</productname> <acronym>JDBC</acronym> driver
is thread safe.
Consequently, if your application uses multiple threads then you do
not have to worry about complex algorithms to ensure that only one thread
uses the database at a time.
</para>
<para>
If a thread attempts to use the connection while another one is
using it, it will wait until the other thread has finished its
current operation. If the operation is a regular <acronym>SQL</acronym>
statement, then the operation consists of sending the statement and
retrieving any <classname>ResultSet</classname> (in full). If it
is a fast-path call (e.g., reading a block
from a large object) then it consists of
sending and retrieving the respective data.
</para>
<para>
This is fine for applications and applets but can cause a
performance problem with servlets. If you have several threads
performing queries then each but one will pause.
To solve this, you are advised to create a pool of connections.
When ever a thread needs to use the database, it asks a manager
class for a <classname>Connection</classname> object. The manager
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 using the connection, it returns it to the manager
which 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 is dead. The down side of a connection pool is
that it increases the load on the server because a new session is
created for each <classname>Connection</classname> object. It is
up to you and your applications' requirements.
</para>
</chapter>
<chapter id="datasource">
<title>Connection Pools and Data Sources</title>
<indexterm zone="datasource">
<primary>connection pool</primary>
<secondary sortas="JDBC">in JDBC</secondary>
</indexterm>
<indexterm zone="datasource">
<primary>DataSource</primary>
</indexterm>
<para>
<acronym>JDBC</acronym> 2 introduced standard connection pooling features in an
add-on <acronym>API</acronym> known as the <acronym>JDBC</acronym> 2.0 Optional
Package (also known as the <acronym>JDBC</acronym> 2.0
Standard Extension). These features have since been included in
the core <acronym>JDBC</acronym> 3 <acronym>API</acronym>.
</para>
<sect1 id="ds-intro">
<title>Overview</title>
<para>
The <acronym>JDBC</acronym> <acronym>API</acronym> provides a client
and a server interface for connection pooling. The client
interface is <literal>javax.sql.DataSource</literal>,
which is what application code will typically use to
acquire a pooled database connection. The server interface
is <literal>javax.sql.ConnectionPoolDataSource</literal>,
which is how most application servers will interface with
the <productname>PostgreSQL</productname> <acronym>JDBC</acronym>
driver.
</para>
<para>
In an application server environment, the
application server configuration will typically refer to
the <productname>PostgreSQL</productname>
<literal>ConnectionPoolDataSource</literal> implementation,
while the application component code will typically acquire a
<literal>DataSource</literal> implementation provided by
the application server (not by
<productname>PostgreSQL</productname>).
</para>
<para>
For an environment without an application server,
<productname>PostgreSQL</productname> provides two implementations
of <literal>DataSource</literal> which an application can use
directly. One implementation performs connection pooling,
while the other simply provides access to database connections
through the <literal>DataSource</literal> interface without
any pooling. Again, these implementations should not be used
in an application server environment unless the application
server does not support the
<literal>ConnectionPoolDataSource</literal> interface.
</para>
</sect1>
<sect1 id="ds-cpds">
<title>Application Servers: <classname>ConnectionPoolDataSource</classname></title>
<para>
<productname>PostgreSQL</productname> includes one implementation
of <classname>ConnectionPoolDataSource</classname> named
<classname>org.postgresql.ds.PGConnectionPoolDataSource</classname>.
</para>
<para>
<acronym>JDBC</acronym> requires that a
<classname>ConnectionPoolDataSource</classname> be configured via
JavaBean properties, shown in <xref linkend="ds-cpds-props"/>,
so there are get and set methods for each of these properties.
</para>
<table id="ds-cpds-props">
<title><classname>ConnectionPoolDataSource</classname> Configuration Properties</title>
<tgroup cols="3">
<thead>
<row>
<entry>Property</entry>
<entry>Type</entry>
<entry>Description</entry>
</row>
</thead>
<tbody>
<row>
<entry><literal>serverName</literal></entry>
<entry><type>String</type></entry>
<entry><productname>PostgreSQL</productname> database server
host name</entry>
</row>
<row>
<entry><literal>databaseName</literal></entry>
<entry><type>String</type></entry>
<entry><productname>PostgreSQL</productname> database name</entry>
</row>
<row>
<entry><literal>portNumber</literal></entry>
<entry><type>int</type></entry>
<entry>
TCP port which the <productname>PostgreSQL</productname>
database server is listening on (or 0 to use the default port)
</entry>
</row>
<row>
<entry><literal>user</literal></entry>
<entry><type>String</type></entry>
<entry>User used to make database connections</entry>
</row>
<row>
<entry><literal>password</literal></entry>
<entry><type>String</type></entry>
<entry>Password used to make database connections</entry>
</row>
<row>
<entry><literal>ssl</literal></entry>
<entry><type>boolean</type></entry>
<entry>
If <literal>true</literal>, use SSL encrypted connections
(default <literal>false</literal>)
</entry>
</row>
<row>
<entry><literal>sslfactory</literal></entry>
<entry><type>String</type></entry>
<entry>
Custom <classname>javax.net.ssl.SSLSocketFactory</classname>
class name (see <xref linkend="ssl-factory"/>)
</entry>
</row>
<row>
<entry><literal>defaultAutoCommit</literal></entry>
<entry><type>boolean</type></entry>
<entry>
Whether connections should have autocommit enabled or disabled
when they are supplied to the caller. The default is
<literal>false</literal>, to disable autocommit.
</entry>
</row>
</tbody>
</tgroup>
</table>
<para>
Many application servers use a properties-style syntax to
configure these properties, so it would not be unusual to enter
properties as a block of text. If the application server provides
a single area to enter all the properties, they might be listed
like this:
<programlisting>
serverName=localhost
databaseName=test
user=testuser
password=testpassword
</programlisting>
Or, if semicolons are used as separators instead of newlines, it
could look like this:
<programlisting>
serverName=localhost;databaseName=test;user=testuser;password=testpassword
</programlisting>
</para>
</sect1>
<sect1 id="ds-ds">
<title>Applications: <classname>DataSource</classname></title>
<para><productname>PostgreSQL</productname> includes two
implementations of <literal>DataSource</literal>
, as shown in <xref linkend="ds-ds-imp"/>. One that does
pooling and the other that does not.
The pooling implementation does not actually close connections
when the client calls the <literal>close</literal> method, but
instead returns the connections to a pool of available connections
for other clients to use. This avoids any overhead of repeatedly
opening and closing connections, and allows a large number of
clients to share a small number of database connections.</para>
<para>The pooling data-source implementation provided here is not
the most feature-rich in the world. Among other things,
connections are never closed until the pool itself is closed;
there is no way to shrink the pool. As well, connections
requested for users other than the default configured user are
not pooled. Its error handling sometimes cannot remove a broken
connection from the pool. In general it is not recommended to
use the <productname>PostgreSQL</productname> provided connection
pool. Check your application server or check out the excellent
<ulink url="http://commons.apache.org/dbcp/">
jakarta commons DBCP</ulink> project.
</para>
<table id="ds-ds-imp">
<title><classname>DataSource</classname> Implementations</title>
<tgroup cols="2">
<thead>
<row>
<entry>Pooling</entry>
<entry>Implementation Class</entry>
</row>
</thead>
<tbody>
<row>
<entry>No</entry>
<entry><classname>org.postgresql.ds.PGSimpleDataSource</classname></entry>
</row>
<row>
<entry>Yes</entry>
<entry><classname>org.postgresql.ds.PGPoolingDataSource</classname></entry>
</row>
</tbody>
</tgroup>
</table>
<para>
Both implementations use the same configuration scheme.
<acronym>JDBC</acronym> requires that a
<literal>DataSource</literal> be configured via JavaBean
properties, shown in <xref linkend="ds-ds-props"/>, so there
are get and set methods for each of these properties.
</para>
<table id="ds-ds-props">
<title><classname>DataSource</classname> Configuration Properties</title>
<tgroup cols="3">
<thead>
<row>
<entry>Property</entry>
<entry>Type</entry>
<entry>Description</entry>
</row>
</thead>
<tbody>
<row>
<entry><literal>serverName</literal></entry>
<entry><type>String</type></entry>
<entry><productname>PostgreSQL</productname> database server
host name</entry>
</row>
<row>
<entry><literal>databaseName</literal></entry>
<entry><type>String</type></entry>
<entry><productname>PostgreSQL</productname> database name</entry>
</row>
<row>
<entry><literal>portNumber</literal></entry>
<entry><type>int</type></entry>
<entry>TCP port which the
<productname>PostgreSQL</productname> database server is
listening on (or 0 to use the default port)</entry>
</row>
<row>
<entry><literal>user</literal></entry>
<entry><type>String</type></entry>
<entry>User used to make database connections</entry>
</row>
<row>
<entry><literal>password</literal></entry>
<entry><type>String</type></entry>
<entry>Password used to make database connections</entry>
</row>
<row>
<entry><literal>ssl</literal></entry>
<entry><type>boolean</type></entry>
<entry>
If <literal>true</literal>, use SSL encrypted connections
(default <literal>false</literal>)
</entry>
</row>
<row>
<entry><literal>sslfactory</literal></entry>
<entry><type>String</type></entry>
<entry>
Custom <classname>javax.net.ssl.SSLSocketFactory</classname>
class name (see <xref linkend="ssl-factory"/>)
</entry>
</row>
</tbody>
</tgroup>
</table>
<para>The pooling implementation requires some additional
configuration properties, which are shown in <xref linkend="ds-ds-xprops"/>.</para>
<table id="ds-ds-xprops">
<title>Additional Pooling <classname>DataSource</classname> Configuration Properties</title>
<tgroup cols="3">
<thead>
<row>
<entry>Property</entry>
<entry>Type</entry>
<entry>Description</entry>
</row>
</thead>
<tbody>
<row>
<entry><literal>dataSourceName</literal></entry>
<entry><type>String</type></entry>
<entry>Every pooling <literal>DataSource</literal> must have a
unique name.</entry>
</row>
<row>
<entry><literal>initialConnections</literal></entry>
<entry><type>int</type></entry>
<entry>The number of database connections to be created
when the pool is initialized.</entry>
</row>
<row>
<entry><literal>maxConnections</literal></entry>
<entry><type>int</type></entry>
<entry>The maximum number of open database connections to
allow. When more connections are requested, the caller
will hang until a connection is returned to the pool.</entry>
</row>
</tbody>
</tgroup>
</table>
<para><xref linkend="ds-example"/> shows an example of typical application code using a
pooling <literal>DataSource</literal>.</para>
<example id="ds-example">
<title><literal>DataSource</literal> Code Example</title>
<para>
Code to initialize a pooling <classname>DataSource</classname> might look like this:
<programlisting>
PGPoolingDataSource source = new PGPoolingDataSource();
source.setDataSourceName("A Data Source");
source.setServerName("localhost");
source.setDatabaseName("test");
source.setUser("testuser");
source.setPassword("testpassword");
source.setMaxConnections(10);
</programlisting>
Then code to use a connection from the pool might look
like this. Note that it is critical that the connections
are eventually closed. Else the pool will <quote>leak</quote> connections and
will eventually lock all the clients out.
<programlisting>
Connection conn = null;
try {
conn = source.getConnection();
// use connection
} catch (SQLException e) {
// log error
} finally {
if (con != null) {
try { conn.close(); } catch (SQLException e) {}
}
}
</programlisting>
</para>
</example>
</sect1>
<sect1 id="tomcat">
<title>Tomcat setup</title>
<indexterm zone="tomcat">
<primary>tomcat</primary>
</indexterm>
<note>
<para>
The postgresql.jar file must be placed in $CATALINA_HOME/common/lib
in both Tomcat 4 and 5.
</para>
</note>
<para>
The absolute easiest way to set this up in either tomcat instance
is to use the admin web application that comes with Tomcat, simply
add the datasource to the context you want to use it in.
</para>
<para>
Setup for Tomcat 4 place the following inside the <Context> tag
inside conf/server.xml
<programlisting lang="xml">
<![CDATA[
<Resource name="jdbc/postgres" scope="Shareable" type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/postgres">
<parameter>
<name>validationQuery</name>
<value>select version();</value>
</parameter>
<parameter>
<name>url</name>
<value>jdbc:postgresql://localhost/davec</value>
</parameter>
<parameter>
<name>password</name>
<value>davec</value>
</parameter>
<parameter>
<name>maxActive</name>
<value>4</value>
</parameter>
<parameter>
<name>maxWait</name>
<value>5000</value>
</parameter>
<parameter>
<name>driverClassName</name>
<value>org.postgresql.Driver</value>
</parameter>
<parameter>
<name>username</name>
<value>davec</value>
</parameter>
<parameter>
<name>maxIdle</name>
<value>2</value>
</parameter>
</ResourceParams>]]>
</programlisting>
</para>
<para>
Setup for Tomcat 5, you can use the above method, except that it
goes inside the <DefaultContext> tag inside the <Host>
tag. eg. <Host> ... <DefaultContext> ...
</para>
<para>
Alternatively there is a conf/Catalina/hostname/context.xml file.
For example http://localhost:8080/servlet-example has a directory
$CATALINA_HOME/conf/Catalina/localhost/servlet-example.xml file.
Inside this file place the above xml inside the <Context> tag
</para>
<para>
Then you can use the following code to access the connection.
<programlisting lang="java">
import javax.naming.*;
import javax.sql.*;
import java.sql.*;
public class DBTest
{
String foo = "Not Connected";
int bar = -1;
public void init()
{
try
{
Context ctx = new InitialContext();
if(ctx == null )
throw new Exception("Boom - No Context");
// /jdbc/postgres is the name of the resource above
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/postgres");
if (ds != null)
{
Connection conn = ds.getConnection();
if(conn != null)
{
foo = "Got Connection "+conn.toString();
Statement stmt = conn.createStatement();
ResultSet rst = stmt.executeQuery("select id, foo, bar from testdata");
if(rst.next()) {
foo=rst.getString(2);
bar=rst.getInt(3);
}
conn.close();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public String getFoo() { return foo; }
public int getBar() { return bar;}
}
</programlisting>
</para>
</sect1>
<sect1 id="jndi">
<title>Data Sources and <acronym>JNDI</acronym></title>
<indexterm zone="jndi">
<primary>JNDI</primary>
</indexterm>
<para>
All the <literal>ConnectionPoolDataSource</literal> and
<literal>DataSource</literal> implementations can be stored
in <acronym>JNDI</acronym>. In the case of the nonpooling
implementations, a new instance will be created every time the
object is retrieved from <acronym>JNDI</acronym>, with the
same settings as the instance that was stored. For the
pooling implementations, the same instance will be retrieved
as long as it is available (e.g., not a different
<acronym>JVM</acronym> retrieving the pool from
<acronym>JNDI</acronym>), or a new instance with the same
settings created otherwise.
</para>
<para>
In the application server environment, typically the
application server's <literal>DataSource</literal> instance
will be stored in <acronym>JNDI</acronym>, instead of the
<productname>PostgreSQL</productname>
<literal>ConnectionPoolDataSource</literal> implementation.
</para>
<para>
In an application environment, the application may store
the <literal>DataSource</literal> in <acronym>JNDI</acronym>
so that it doesn't have to make a reference to the
<literal>DataSource</literal> available to all application
components that may need to use it. An example of this is
shown in <xref linkend="ds-jndi"/>.
</para>
<example id="ds-jndi">
<title><classname>DataSource</classname> <acronym>JNDI</acronym> Code Example</title>
<para>
Application code to initialize a pooling <classname>DataSource</classname> and add
it to <acronym>JNDI</acronym> might look like this:
<programlisting>
PGPoolingDataSource source = new PGPoolingDataSource();
source.setDataSourceName("A Data Source");
source.setServerName("localhost");
source.setDatabaseName("test");
source.setUser("testuser");
source.setPassword("testpassword");
source.setMaxConnections(10);
new InitialContext().rebind("DataSource", source);
</programlisting>
Then code to use a connection from the pool might look
like this:
<programlisting>
Connection conn = null;
try {
DataSource source = (DataSource)new InitialContext().lookup("DataSource");
conn = source.getConnection();
// use connection
} catch (SQLException e) {
// log error
} catch (NamingException e) {
// DataSource wasn't found in JNDI
} finally {
if (con != null) {
try { conn.close(); } catch (SQLException e) {}
}
}
</programlisting>
</para>
</example>
</sect1>
</chapter>
<chapter id="reading">
<title>Further Reading</title>
<para>
If you have not yet read it, you are advised you read the
<acronym>JDBC</acronym> <acronym>API</acronym> Documentation
(supplied with Oracle's <acronym>JDK</acronym>) and the
<acronym>JDBC</acronym> Specification. Both are available from
<ulink
url="http://www.oracle.com/technetwork/java/javase/jdbc/index.html"></ulink>.
</para>
<para>
<ulink
url="http://jdbc.postgresql.org/index.html"></ulink>
contains updated information not included in this manual including
Javadoc class documentation and a FAQ. Additionally it
offers precompiled drivers.
</para>
</chapter>
</book>
|