|
| 1 | +/* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.*/ |
| 2 | +/** |
| 3 | + * DESCRIPTION |
| 4 | + * |
| 5 | + * This code sample illustrates the usage of below Oracle column data types - |
| 6 | + * <p> |
| 7 | + * DATE, TIMESTAMP, TIMESTAMP WITH TIME ZONE and TIMESTAMP WITH LOCAL TIME ZONE |
| 8 | + * </p> |
| 9 | + * The code sample creates a simple table with these data types and performs |
| 10 | + * insert, update, and retrieval operation on the table. |
| 11 | + * <p> |
| 12 | + * It is required that applications have Oracle JDBC driver jar (ojdbc8.jar) in |
| 13 | + * the class-path, and that the database backend supports SQL (this sample uses |
| 14 | + * an Oracle Database). |
| 15 | + * </p> |
| 16 | + * <p> |
| 17 | + * To run the sample, you must enter the DB user's password from the console, |
| 18 | + * and optionally specify the DB user and/or connect URL on the command-line. |
| 19 | + * You can also modify these values in this file and recompile the code. |
| 20 | + * </p> |
| 21 | + * |
| 22 | + * java DateTimeStampSample -l <url> -u <user> |
| 23 | + * |
| 24 | + */ |
| 25 | +import java.io.BufferedReader; |
| 26 | +import java.io.InputStreamReader; |
| 27 | +import java.sql.Connection; |
| 28 | +import java.sql.Date; |
| 29 | +import java.sql.PreparedStatement; |
| 30 | +import java.sql.ResultSet; |
| 31 | +import java.sql.SQLException; |
| 32 | +import java.sql.SQLType; |
| 33 | +import java.sql.Statement; |
| 34 | +import java.sql.Timestamp; |
| 35 | +import java.time.LocalDateTime; |
| 36 | +import java.time.ZonedDateTime; |
| 37 | + |
| 38 | +import oracle.jdbc.OracleType; |
| 39 | +import oracle.jdbc.pool.OracleDataSource; |
| 40 | + |
| 41 | +public class DateTimeStampSample { |
| 42 | + |
| 43 | + // Either modify user and url values to point your DB or |
| 44 | + // provide these values using command line arguments. |
| 45 | + private static String user = "myuser"; |
| 46 | + private static String password = "mypassword"; |
| 47 | + private static String url = "jdbc:oracle:thin:@//myhost:1521/myservice"; |
| 48 | + |
| 49 | + public static void main(String[] args) throws Exception { |
| 50 | + |
| 51 | + // These 2 can be either default or from command-line |
| 52 | + url = getOptionValue(args, "-l", url); |
| 53 | + user = getOptionValue(args, "-u", user); |
| 54 | + |
| 55 | + // DB user's Password must be entered |
| 56 | + readPassword(" Enter Password for " + user + ": "); |
| 57 | + |
| 58 | + DateTimeStampSample demo = new DateTimeStampSample(); |
| 59 | + demo.run(); |
| 60 | + } |
| 61 | + |
| 62 | + void run() throws SQLException { |
| 63 | + try (Connection conn = getConnection()) { |
| 64 | + |
| 65 | + // Truncate the existing table |
| 66 | + truncateTable(conn); |
| 67 | + |
| 68 | + // employee details |
| 69 | + int empId = 1001; |
| 70 | + Date dateOfBirth = Date.valueOf("1988-09-04"); |
| 71 | + LocalDateTime joiningDate = LocalDateTime.now(); |
| 72 | + ZonedDateTime dateOfResignation = ZonedDateTime |
| 73 | + .parse("2018-05-09T22:22:22-08:00[PST8PDT]"); |
| 74 | + Timestamp dateOfLeaving = Timestamp.valueOf(LocalDateTime.now()); |
| 75 | + Employee e = new Employee(empId, dateOfBirth, joiningDate, |
| 76 | + dateOfResignation, dateOfLeaving); |
| 77 | + show("\nInsert employee record into table with id = "+empId); |
| 78 | + insertEmployee(e, conn); |
| 79 | + |
| 80 | + show("\nEmployee details of employee = " + empId); |
| 81 | + Employee emp = getEmployeeDetails(1001, conn); |
| 82 | + if (emp != null) |
| 83 | + emp.print(); |
| 84 | + |
| 85 | + show("Update the employee details of employee = " + empId); |
| 86 | + updateEmployee(empId, conn); |
| 87 | + |
| 88 | + show("\nUpdated details of employee = " + empId); |
| 89 | + Employee emp1 = getEmployeeDetails(1001, conn); |
| 90 | + if (emp1 != null) |
| 91 | + emp1.print(); |
| 92 | + |
| 93 | + show("JDBCDateTimeSample demo completes."); |
| 94 | + } |
| 95 | + |
| 96 | + } |
| 97 | + |
| 98 | + /** |
| 99 | + * Inserts employee data into table using given connection. |
| 100 | + * |
| 101 | + * @param emp |
| 102 | + * Employee data |
| 103 | + * @param conn |
| 104 | + * Connection to be used to insert the employee data. |
| 105 | + * @throws SQLException |
| 106 | + */ |
| 107 | + private void insertEmployee(Employee emp, Connection conn) |
| 108 | + throws SQLException { |
| 109 | + final String insertQuery = "INSERT INTO EMP_DATE_JDBC_SAMPLE VALUES(?,?,?,?,?)"; |
| 110 | + try (PreparedStatement pstmt = conn.prepareStatement(insertQuery)) { |
| 111 | + SQLType dataType = null; |
| 112 | + |
| 113 | + pstmt.setInt(1, emp.getId()); |
| 114 | + pstmt.setDate(2, emp.getDateOfBirth()); |
| 115 | + dataType = OracleType.TIMESTAMP_WITH_LOCAL_TIME_ZONE; |
| 116 | + pstmt.setObject(3, emp.getJoiningDate(), dataType); |
| 117 | + dataType = OracleType.TIMESTAMP_WITH_TIME_ZONE; |
| 118 | + pstmt.setObject(4, emp.getResignationDate(), dataType); |
| 119 | + pstmt.setTimestamp(5, emp.getDateOfLeaving()); |
| 120 | + pstmt.executeUpdate(); |
| 121 | + show("Employee record inserted successfully."); |
| 122 | + } |
| 123 | + } |
| 124 | + |
| 125 | + /** |
| 126 | + * Fetches the employee data for given employee id. |
| 127 | + * |
| 128 | + * @param id |
| 129 | + * Employee id. |
| 130 | + * @param conn |
| 131 | + * Connection to be used to fetch employee data. |
| 132 | + * @return |
| 133 | + * @throws SQLException |
| 134 | + */ |
| 135 | + private Employee getEmployeeDetails(int id, Connection conn) |
| 136 | + throws SQLException { |
| 137 | + final String selectQuery = "SELECT EMP_ID, DATE_OF_BIRTH, DATE_OF_JOINING, " |
| 138 | + + "DATE_OF_RESIGNATION, DATE_OF_LEAVING FROM EMP_DATE_JDBC_SAMPLE WHERE EMP_ID = ?"; |
| 139 | + try (PreparedStatement pstmt = conn.prepareStatement(selectQuery)) { |
| 140 | + pstmt.setInt(1, id); |
| 141 | + try (ResultSet rs = pstmt.executeQuery()) { |
| 142 | + if (rs.next()) { |
| 143 | + int employeeId = rs.getInt(1); |
| 144 | + Date datOfBirth = rs.getDate(2); |
| 145 | + LocalDateTime dateOfJoining = rs.getObject(3, LocalDateTime.class); |
| 146 | + ZonedDateTime dateOfResignation = rs |
| 147 | + .getObject(4, ZonedDateTime.class); |
| 148 | + Timestamp dateOfLeaving = rs.getTimestamp(5); |
| 149 | + return new Employee(employeeId, datOfBirth, dateOfJoining, |
| 150 | + dateOfResignation, dateOfLeaving); |
| 151 | + } else { |
| 152 | + show("Employee record not found in the database."); |
| 153 | + return null; |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + } |
| 158 | + } |
| 159 | + |
| 160 | + /** |
| 161 | + * Updates the employee record for given employee id. |
| 162 | + * |
| 163 | + * @param id |
| 164 | + * Employee id. |
| 165 | + * @param conn |
| 166 | + * Connection to be used to update employee data. |
| 167 | + * @throws SQLException |
| 168 | + */ |
| 169 | + private void updateEmployee(int id, Connection conn) throws SQLException { |
| 170 | + final String updateQuery = "UPDATE EMP_DATE_JDBC_SAMPLE SET DATE_OF_JOINING=? WHERE EMP_ID =?"; |
| 171 | + try (PreparedStatement pstmt = conn.prepareStatement(updateQuery)) { |
| 172 | + SQLType dataType = OracleType.TIMESTAMP_WITH_LOCAL_TIME_ZONE; |
| 173 | + pstmt.setObject(1, |
| 174 | + ZonedDateTime.parse("2015-12-09T22:22:22-08:00[PST8PDT]"), dataType); |
| 175 | + pstmt.setInt(2, id); |
| 176 | + int updateCount = pstmt.executeUpdate(); |
| 177 | + show("Successfully updated employee details."); |
| 178 | + } |
| 179 | + } |
| 180 | + |
| 181 | + private void truncateTable(Connection conn) { |
| 182 | + final String sql = "TRUNCATE TABLE EMP_DATE_JDBC_SAMPLE"; |
| 183 | + try (Statement st = conn.createStatement()) { |
| 184 | + st.executeQuery(sql); |
| 185 | + show("Table truncated successfully."); |
| 186 | + } catch (SQLException e) { |
| 187 | + showError("Truncate table operation failed.", e); |
| 188 | + } |
| 189 | + } |
| 190 | + |
| 191 | + static Connection getConnection() throws SQLException { |
| 192 | + OracleDataSource ods = new OracleDataSource(); |
| 193 | + ods.setURL(url); |
| 194 | + ods.setUser(user); |
| 195 | + ods.setPassword(password); |
| 196 | + Connection conn = ods.getConnection(); |
| 197 | + return conn; |
| 198 | + } |
| 199 | + |
| 200 | + private static void show(String msg) { |
| 201 | + System.out.println(msg); |
| 202 | + } |
| 203 | + |
| 204 | + static void showError(String msg, Throwable exc) { |
| 205 | + System.out.println(msg + " hit error: " + exc.getMessage()); |
| 206 | + } |
| 207 | + |
| 208 | + // Get specified option value from command-line, or use default value |
| 209 | + static String getOptionValue(String args[], String optionName, |
| 210 | + String defaultVal) { |
| 211 | + String argValue = ""; |
| 212 | + try { |
| 213 | + int i = 0; |
| 214 | + String arg = ""; |
| 215 | + boolean found = false; |
| 216 | + while (i < args.length) { |
| 217 | + arg = args[i++]; |
| 218 | + if (arg.equals(optionName)) { |
| 219 | + if (i < args.length) |
| 220 | + argValue = args[i++]; |
| 221 | + if (argValue.startsWith("-") || argValue.equals("")) { |
| 222 | + argValue = defaultVal; |
| 223 | + } |
| 224 | + found = true; |
| 225 | + } |
| 226 | + } |
| 227 | + |
| 228 | + if (!found) { |
| 229 | + argValue = defaultVal; |
| 230 | + } |
| 231 | + } catch (Exception e) { |
| 232 | + showError("getOptionValue", e); |
| 233 | + } |
| 234 | + return argValue; |
| 235 | + } |
| 236 | + |
| 237 | + /** |
| 238 | + * Reads the password from console. |
| 239 | + * |
| 240 | + * @param prompt |
| 241 | + * @throws Exception |
| 242 | + */ |
| 243 | + static void readPassword(String prompt) throws Exception { |
| 244 | + if (System.console() != null) { |
| 245 | + char[] pchars = System.console().readPassword("\n[%s]", prompt); |
| 246 | + if (pchars != null) { |
| 247 | + password = new String(pchars); |
| 248 | + java.util.Arrays.fill(pchars, ' '); |
| 249 | + } |
| 250 | + } else { |
| 251 | + BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); |
| 252 | + show(prompt); |
| 253 | + password = r.readLine(); |
| 254 | + } |
| 255 | + } |
| 256 | + |
| 257 | + /** |
| 258 | + * A simple class to represent the employee table structure. An instance of |
| 259 | + * this class represents a row in employee table. |
| 260 | + */ |
| 261 | + static class Employee { |
| 262 | + private int id; |
| 263 | + private Date dateOfBirth; |
| 264 | + private LocalDateTime joiningDate; |
| 265 | + private ZonedDateTime dateOfResignation; |
| 266 | + private Timestamp dateOfLeaving; |
| 267 | + |
| 268 | + Employee(int id, Date dateOfBirth, LocalDateTime joiningDate, |
| 269 | + ZonedDateTime dateOfResignation, Timestamp dateOfLeaving) { |
| 270 | + this.id = id; |
| 271 | + this.dateOfBirth = dateOfBirth; |
| 272 | + this.joiningDate = joiningDate; |
| 273 | + this.dateOfResignation = dateOfResignation; |
| 274 | + this.dateOfLeaving = dateOfLeaving; |
| 275 | + } |
| 276 | + |
| 277 | + int getId() { |
| 278 | + return id; |
| 279 | + } |
| 280 | + |
| 281 | + Date getDateOfBirth() { |
| 282 | + return this.dateOfBirth; |
| 283 | + } |
| 284 | + |
| 285 | + LocalDateTime getJoiningDate() { |
| 286 | + return this.joiningDate; |
| 287 | + } |
| 288 | + |
| 289 | + ZonedDateTime getResignationDate() { |
| 290 | + return this.dateOfResignation; |
| 291 | + } |
| 292 | + |
| 293 | + Timestamp getDateOfLeaving() { |
| 294 | + return this.dateOfLeaving; |
| 295 | + } |
| 296 | + |
| 297 | + void print() { |
| 298 | + show("/----------------------------------------------------------------/"); |
| 299 | + show("ID : " + id); |
| 300 | + show("Date Of Birth : " + dateOfBirth); |
| 301 | + show("Joining Date : " + joiningDate); |
| 302 | + show("Resignation Date : " + dateOfResignation); |
| 303 | + show("Date of Leaving : " + dateOfLeaving); |
| 304 | + show("/----------------------------------------------------------------/\n"); |
| 305 | + } |
| 306 | + } |
| 307 | +} |
0 commit comments