|
| 1 | +/* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.*/ |
| 2 | + |
| 3 | +/* |
| 4 | + DESCRIPTION |
| 5 | +
|
| 6 | + This code sample demonstrates usage of VARRAY data structure in PL/SQL. |
| 7 | + This capability was added in the JDBC thin driver in 18c. |
| 8 | + To run the sample, you must enter the DB user's password from the |
| 9 | + console, and optionally specify the DB user and/or connect URL on |
| 10 | + the command-line. You can also modify these values in this file |
| 11 | + and recompile the code. |
| 12 | + java VARRAYSample -l <url> -u <user> |
| 13 | + */ |
| 14 | + |
| 15 | +/*import java.sql.*; |
| 16 | +import oracle.sql.*; |
| 17 | +import oracle.jdbc.*; */ |
| 18 | +import java.io.BufferedReader; |
| 19 | +import java.io.InputStreamReader; |
| 20 | +import java.math.BigDecimal; |
| 21 | +import java.sql.Array; |
| 22 | +import java.sql.Connection; |
| 23 | +import java.sql.PreparedStatement; |
| 24 | +import java.sql.ResultSet; |
| 25 | +import java.sql.SQLException; |
| 26 | +import java.sql.Statement; |
| 27 | + |
| 28 | +import oracle.jdbc.OracleArray; |
| 29 | +import oracle.jdbc.OracleConnection; |
| 30 | +import oracle.jdbc.pool.OracleDataSource; |
| 31 | + |
| 32 | +public class VARRAYSample { |
| 33 | + |
| 34 | + final static String DEFAULT_URL = "jdbc:oracle:thin:@//myhost:myport/myservice"; |
| 35 | + final static String DEFAULT_USER = "myuser"; |
| 36 | + final static String DEFAULT_PASSWORD = "mypassword"; |
| 37 | + |
| 38 | + // You must provide non-default values for all 3 parameters to execute the program |
| 39 | + static String url = DEFAULT_URL; |
| 40 | + static String user = DEFAULT_USER; |
| 41 | + static String password = DEFAULT_PASSWORD; |
| 42 | + |
| 43 | + // Connection object for VARRAY sample. |
| 44 | + // The sample uses only one connection for all VARRAY |
| 45 | + // operations in this demo program. |
| 46 | + private Connection conn; |
| 47 | + |
| 48 | + /** |
| 49 | + * Entry point of the sample. |
| 50 | + * |
| 51 | + * @param args |
| 52 | + * Command line arguments. Supported command line options: -l <url> |
| 53 | + * -u <user> |
| 54 | + * @throws Exception |
| 55 | + */ |
| 56 | + public static void main(String args[]) throws Exception { |
| 57 | + VARRAYSample vArraySample = new VARRAYSample(); |
| 58 | + |
| 59 | + getRealUserPasswordUrl(args); |
| 60 | + |
| 61 | + // Get a connection and initialize the schema. |
| 62 | + vArraySample.setup(); |
| 63 | + |
| 64 | + // Shows VARRAY usage |
| 65 | + vArraySample.demoVARRAY(); |
| 66 | + |
| 67 | + // Drop table and disconnect from the database. |
| 68 | + vArraySample.cleanup(); |
| 69 | + } |
| 70 | + |
| 71 | + /** |
| 72 | + * Creates Connection to database and drops the demo table if exists |
| 73 | + * @throws SQLException |
| 74 | + */ |
| 75 | + void setup() throws SQLException { |
| 76 | + conn = getConnection(); |
| 77 | + dropTableAndType(); |
| 78 | + } |
| 79 | + |
| 80 | + |
| 81 | + /** |
| 82 | + * Drop the table, type and close the connection |
| 83 | + * @throws SQLException |
| 84 | + */ |
| 85 | + void cleanup() throws SQLException { |
| 86 | + if (conn != null) { |
| 87 | + dropTableAndType(); |
| 88 | + conn.close(); |
| 89 | + conn = null; |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + |
| 94 | + |
| 95 | + /** |
| 96 | + * Shows how to use VArray PLSQL collection |
| 97 | + * @throws SQLException |
| 98 | + */ |
| 99 | + void demoVARRAY() throws SQLException { |
| 100 | + |
| 101 | + // Utility method to create table and type required for demo |
| 102 | + createTableAndType(); |
| 103 | + |
| 104 | + demoVARRAYWihtoutBind(); |
| 105 | + |
| 106 | + demoVARRAYWithBind(); |
| 107 | + } |
| 108 | + |
| 109 | + |
| 110 | + /** |
| 111 | + * Usage of VARRAY with constant object |
| 112 | + * @throws SQLException |
| 113 | + */ |
| 114 | + private void demoVARRAYWihtoutBind() throws SQLException { |
| 115 | + showln("======== demoVARRAYWihtoutBind ========"); |
| 116 | + try (Statement stmt = conn.createStatement()) { |
| 117 | + |
| 118 | + // Insert multiple values of type num_array into single row |
| 119 | + stmt.execute("INSERT INTO varray_table VALUES (num_varray(100, 200))"); |
| 120 | + |
| 121 | + ResultSet rs = stmt.executeQuery("SELECT col1 FROM varray_table"); |
| 122 | + showArrayResultSet(rs); |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + /** |
| 127 | + * Usage of VARRAY with parametric values |
| 128 | + * @throws SQLException |
| 129 | + */ |
| 130 | + private void demoVARRAYWithBind() throws SQLException { |
| 131 | + showln("======== demoVARRAYWithBind ======="); |
| 132 | + try (Statement stmt = conn.createStatement()) { |
| 133 | + |
| 134 | + // Insert a new row with 4 values |
| 135 | + int elements[] = { 300, 400, 500, 600 }; |
| 136 | + // Create a new Array with the above elements with given type |
| 137 | + OracleArray newArray = (OracleArray) ((OracleConnection) conn).createOracleArray("NUM_VARRAY", elements); |
| 138 | + // Create prepared statement to insert values |
| 139 | + try (PreparedStatement ps = conn.prepareStatement("INSERT INTO varray_table VALUES (?)")) { |
| 140 | + // Bind the array values to statement |
| 141 | + ps.setArray(1, newArray); |
| 142 | + ps.execute(); |
| 143 | + |
| 144 | + ResultSet rs = stmt.executeQuery("SELECT col1 FROM varray_table"); |
| 145 | + showArrayResultSet(rs); |
| 146 | + } |
| 147 | + } |
| 148 | + } |
| 149 | + |
| 150 | + // ==============================Utility Methods============================== |
| 151 | + |
| 152 | + /** |
| 153 | + * Creates table with VARRAY type object |
| 154 | + * @throws SQLException |
| 155 | + */ |
| 156 | + private void createTableAndType() throws SQLException { |
| 157 | + try (Statement stmt = conn.createStatement()) { |
| 158 | + // create num_varray with array of elements of type NUMBER |
| 159 | + String sql = "CREATE TYPE num_varray AS VARRAY(10) OF NUMBER(12, 2)"; |
| 160 | + stmt.execute(sql); |
| 161 | + |
| 162 | + // Create table with num_varray with column as VARRAY type |
| 163 | + sql = "CREATE TABLE varray_table (col1 num_varray)"; |
| 164 | + stmt.execute(sql); |
| 165 | + } |
| 166 | + } |
| 167 | + |
| 168 | + /** |
| 169 | + * Drop the table and type |
| 170 | + * @throws SQLException |
| 171 | + */ |
| 172 | + private void dropTableAndType() throws SQLException { |
| 173 | + try (Statement stmt = conn.createStatement()) { |
| 174 | + // Drop the table and type if exists |
| 175 | + stmt.execute("DROP TABLE varray_table"); |
| 176 | + stmt.execute("DROP TYPE num_varray"); |
| 177 | + } catch (SQLException e) { |
| 178 | + // the above drop statements will throw exceptions |
| 179 | + // if the types and tables did not exist before. Just ignore it. |
| 180 | + if (e.getErrorCode() != 942) |
| 181 | + throw new RuntimeException(e); |
| 182 | + else |
| 183 | + showln("INFO: " + e.getMessage()); |
| 184 | + } |
| 185 | + } |
| 186 | + |
| 187 | + /** |
| 188 | + * Gets the connection object |
| 189 | + * @throws SQLException |
| 190 | + */ |
| 191 | + private Connection getConnection() throws SQLException { |
| 192 | + // Create an OracleDataSource instance and set properties |
| 193 | + OracleDataSource ods = new OracleDataSource(); |
| 194 | + ods.setUser(user); |
| 195 | + ods.setPassword(password); |
| 196 | + ods.setURL(url); |
| 197 | + |
| 198 | + return ods.getConnection(); |
| 199 | + } |
| 200 | + |
| 201 | + static void getRealUserPasswordUrl(String args[]) throws Exception { |
| 202 | + // URL can be modified in file, or taken from command-line |
| 203 | + url = getOptionValue(args, "-l", DEFAULT_URL); |
| 204 | + |
| 205 | + // DB user can be modified in file, or taken from command-line |
| 206 | + user = getOptionValue(args, "-u", DEFAULT_USER); |
| 207 | + |
| 208 | + // DB user's password can be modified in file, or explicitly entered |
| 209 | + readPassword(" Password for " + user + ": "); |
| 210 | + } |
| 211 | + |
| 212 | + // Get specified option value from command-line, or use default value |
| 213 | + static String getOptionValue(String args[], String optionName, String defaultVal) { |
| 214 | + String argValue = ""; |
| 215 | + |
| 216 | + try { |
| 217 | + int i = 0; |
| 218 | + String arg = ""; |
| 219 | + boolean found = false; |
| 220 | + |
| 221 | + while (i < args.length) { |
| 222 | + arg = args[i++]; |
| 223 | + if (arg.equals(optionName)) { |
| 224 | + if (i < args.length) |
| 225 | + argValue = args[i++]; |
| 226 | + if (argValue.startsWith("-") || argValue.equals("")) { |
| 227 | + argValue = defaultVal; |
| 228 | + } |
| 229 | + found = true; |
| 230 | + } |
| 231 | + } |
| 232 | + |
| 233 | + if (!found) { |
| 234 | + argValue = defaultVal; |
| 235 | + } |
| 236 | + } catch (Exception e) { |
| 237 | + showError("getOptionValue", e); |
| 238 | + } |
| 239 | + return argValue; |
| 240 | + } |
| 241 | + |
| 242 | + static void readPassword(String prompt) throws Exception { |
| 243 | + if (System.console() == null) { |
| 244 | + BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); |
| 245 | + showln(prompt); |
| 246 | + password = r.readLine(); |
| 247 | + } else { |
| 248 | + char[] pchars = System.console().readPassword("\n[%s]", prompt); |
| 249 | + if (pchars != null) { |
| 250 | + password = new String(pchars); |
| 251 | + java.util.Arrays.fill(pchars, ' '); |
| 252 | + } |
| 253 | + } |
| 254 | + } |
| 255 | + |
| 256 | + // Show message line without new line |
| 257 | + private static void showln(String msg) { |
| 258 | + System.out.println(msg); |
| 259 | + } |
| 260 | + |
| 261 | + static void showError(String msg, Throwable exc) { |
| 262 | + System.out.println(msg + " hit error: " + exc.getMessage()); |
| 263 | + } |
| 264 | + |
| 265 | + /** |
| 266 | + * Display array elements to console. |
| 267 | + * @param rs |
| 268 | + * @throws SQLException |
| 269 | + */ |
| 270 | + public static void showArrayResultSet(ResultSet rs) throws SQLException { |
| 271 | + int line = 0; |
| 272 | + |
| 273 | + while (rs.next()) { |
| 274 | + line++; |
| 275 | + |
| 276 | + showln("Row " + line + " : "); |
| 277 | + Array array = rs.getArray(1); |
| 278 | + |
| 279 | + showln("Array is of type " + ((OracleArray) array).getSQLTypeName()); |
| 280 | + showln("Array element is of type code " + array.getBaseType()); |
| 281 | + |
| 282 | + showln("Array is of length " + ((OracleArray) array).length()); |
| 283 | + |
| 284 | + // get Array elements |
| 285 | + BigDecimal[] values = (BigDecimal[]) array.getArray(); |
| 286 | + |
| 287 | + for (int i = 0; i < values.length; i++) { |
| 288 | + BigDecimal value = values[i]; |
| 289 | + showln(">>Array index " + i + " = " + value.intValue()); |
| 290 | + } |
| 291 | + } |
| 292 | + } |
| 293 | +} |
| 294 | + |
0 commit comments