Advertisement
Guest User

Untitled

a guest
Jun 21st, 2017
281
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.98 KB | None | 0 0
  1. /*
  2. * NOTE:
  3. * THIS PACKAGE CONTAINS ONLY A
  4. * *JDBC SAMPLE* PROGRAM
  5. * JUST TO SHOW THE USAGE OF THE USAGE OF THE BASIC JDBC API!
  6. *
  7. * This is not an example of (good) object-oriented programming ;-)
  8. */
  9.  
  10.  
  11.  
  12. import java.sql.DriverManager;
  13. import java.sql.Connection;
  14. import java.sql.SQLException;
  15. import java.sql.ResultSet;
  16. import java.sql.ResultSetMetaData;
  17.  
  18. import java.io.BufferedReader;
  19. import java.io.InputStreamReader;
  20.  
  21. import java.util.Date;
  22. import java.text.SimpleDateFormat;
  23. import java.text.ParseException;
  24.  
  25.  
  26.  
  27. /*
  28. * UTILITY CLASS for DBIS JDBC SAMPLE program
  29. *
  30. * Author: Prof. Dr. Juergen Waesch, HTWG Konstanz
  31. * Last modified: May 21, 2014
  32. *
  33. */
  34. public class DBISUtils {
  35.  
  36.  
  37. // Debug flag: if set to true, the "debug info" methods print to standard out
  38. private static boolean DEBUG = false;
  39.  
  40.  
  41. // Reference to the JDBC connection
  42. private static Connection theConnection = null;
  43.  
  44.  
  45.  
  46. // TODO: SET "DB_LOGIN" AND "DB_PASSWORD" TO YOUR ORACLE LOGIN AND PASSWORD!!!
  47.  
  48. // User(name) and password used for connecting to the DBS instance
  49. private static final String DB_LOGIN = "dbs22";
  50. private static final String DB_PASSWORD = "georgi.kev";
  51.  
  52.  
  53. // Connection parameters to be used for connecting to the DBIS@HTWG Oracle 12c DBS instance are:
  54. // + jdbc:oracle:thin: -> identifier for the thin Oracle JDBC driver
  55. // + oracle12c.in.htwg-konstanz.de -> host running the Oracle DBS instance
  56. // + 1521 -> port used by the Oracle DBS instance for JDBC connections
  57. // + ora12c -> identifier of the Oracle DBS instance to be connected with
  58.  
  59. // Oracle JDBC-URL pattern is:
  60. // <Oracle-JDBC-Driver-identifier>@<host>:<port>:<instance-identifier>,
  61. // e.g., jdbc:oracle:thin:@<host>:<port>:<instance-identifier>
  62.  
  63.  
  64. // TODO: PROVIDE THE CORRECT ORACLE JDBC-URL!!!
  65.  
  66. // JDBC-URL to connect to the DBIS@HTWG Oracle DBS instance
  67. private static final String DB_CONNPARAMSTRING = "jdbc:oracle:thin:@oracle12c.in.htwg-konstanz.de:1521:ora12c";
  68.  
  69.  
  70.  
  71. /*
  72. * Set the debug flag:
  73. * if set to true, the "debug info" methods print to standard out
  74. */
  75. public static void setDebugFlag(boolean theDebugFlag) {
  76.  
  77. DEBUG = theDebugFlag;
  78.  
  79. }
  80.  
  81.  
  82. /*
  83. * Create or return a JDBC connection to connect to an Oracle DBS instance
  84. * (with auto-commit disabled and serializability as isolation level)
  85. */
  86. public static Connection getConnection() throws SQLException {
  87.  
  88. //if JDBC connection does not already exist, create it
  89. if (theConnection == null) {
  90.  
  91. System.out.println();
  92.  
  93. System.out.println("Loading Oracle JDBC driver ...");
  94. DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
  95. System.out.println("... Oracle JDBC driver loaded!");
  96.  
  97. System.out.println();
  98.  
  99. System.out.println("Connecting to DBS instance ...");
  100. System.out.println(" - JDBC-URL: " + DB_CONNPARAMSTRING);
  101. System.out.println(" - User : " + DB_LOGIN);
  102. Connection aConnection = DriverManager.getConnection(DB_CONNPARAMSTRING, DB_LOGIN, DB_PASSWORD);
  103. System.out.println("... connected to DBS instance!");
  104.  
  105. System.out.println();
  106.  
  107. System.out.println("Setting transaction parameters for connection ...");
  108.  
  109. // Set the transaction isolation level to serializable:
  110. // to be sure that the DBS uses serializability as correctness criterion
  111. System.out.println(" - transaction isolation level is : " + aConnection.getTransactionIsolation()
  112. + " (" + decodeTransactionIsolationLevel(aConnection.getTransactionIsolation()) + ")");
  113. aConnection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
  114. System.out.println(" - transaction isolation level is now: " + aConnection.getTransactionIsolation()
  115. + " (" + decodeTransactionIsolationLevel(aConnection.getTransactionIsolation()) + ")");
  116.  
  117. // Turn off auto-commit to respect the transaction borders:
  118. // transactions are not automatically/implicitly committed after each SQL DML statement
  119. System.out.println(" - auto commit is : " + aConnection.getAutoCommit());
  120. aConnection.setAutoCommit(false);
  121. System.out.println(" - auto commit is now : " + aConnection.getAutoCommit());
  122.  
  123. System.out.println("... transaction parameters for connection set!");
  124.  
  125. System.out.println();
  126.  
  127. System.out.println("JDBC connection ready to use!");
  128. System.out.println();
  129.  
  130. theConnection = aConnection;
  131. }
  132.  
  133. return theConnection;
  134.  
  135. }
  136.  
  137.  
  138.  
  139. /*
  140. * Decode SQL transaction isolation levels
  141. */
  142. public static String decodeTransactionIsolationLevel(int transactionIsolationLevel) {
  143.  
  144. switch (transactionIsolationLevel) {
  145.  
  146. case Connection.TRANSACTION_NONE:
  147. return "No transactions supported";
  148. case Connection.TRANSACTION_READ_COMMITTED:
  149. return "Read committed";
  150. case Connection.TRANSACTION_READ_UNCOMMITTED:
  151. return "Read uncommitted";
  152. case Connection.TRANSACTION_REPEATABLE_READ:
  153. return "Repeatable read";
  154. case Connection.TRANSACTION_SERIALIZABLE:
  155. return "Serializable";
  156. default:
  157. return "Unknown trasaction isolation level";
  158. }
  159.  
  160. }
  161.  
  162.  
  163.  
  164. /*
  165. * Decode and print a single SQL exception to standard output
  166. */
  167. public static void decodeAndPrintSQLException(SQLException se) {
  168.  
  169. System.out.println();
  170.  
  171. System.out.println("*** SQL exception: ***********");
  172. System.out.println(" - Error message : " + se.getMessage());
  173. System.out.println(" - SQL state : " + se.getSQLState());
  174. System.out.println(" - Vendor error code : " + se.getErrorCode());
  175. System.out.println("******************************");
  176. }
  177.  
  178.  
  179.  
  180. /*
  181. * Decode and print *all* chained SQL exceptions
  182. */
  183. public static void decodeAndPrintAllSQLExceptions(SQLException anSQLException) {
  184.  
  185. SQLException theActualSQLException = anSQLException;
  186.  
  187. while (theActualSQLException != null) {
  188.  
  189. decodeAndPrintSQLException(theActualSQLException);
  190. theActualSQLException = theActualSQLException.getNextException();
  191.  
  192. }
  193.  
  194. }
  195.  
  196.  
  197.  
  198. /*
  199. * "Simple" generic print method to
  200. * print the data of any JDBC result set to standard output
  201. *
  202. * Note: method can be improved / output formatting can be beautified
  203. */
  204. public static int printResultSet(ResultSet rset) {
  205.  
  206. int noRows = 0;
  207.  
  208. try {
  209.  
  210. ResultSetMetaData rsmd = rset.getMetaData();
  211.  
  212. while(rset.next()){
  213.  
  214. if (noRows == 0) {
  215.  
  216. for(int i=1; i<=rsmd.getColumnCount(); i++) {
  217. System.out.print(rsmd.getColumnName(i));
  218. if (i == rsmd.getColumnCount()) {
  219. System.out.print("\n");
  220. }
  221. else {
  222. System.out.print("\t");
  223. }
  224. }
  225. }
  226.  
  227. for(int col=1; col<=rsmd.getColumnCount(); col++) {
  228. System.out.print(rset.getObject(col));
  229. if (col == rsmd.getColumnCount()) {
  230. System.out.print("\n");
  231. }
  232. else {
  233. System.out.print("\t");
  234. }
  235. }
  236.  
  237. noRows++;
  238.  
  239. }
  240.  
  241. } catch (SQLException se) {
  242.  
  243. decodeAndPrintAllSQLExceptions(se);
  244.  
  245. return -1;
  246.  
  247. }
  248.  
  249.  
  250. if (noRows == 0) {
  251.  
  252. System.out.println("No rows found!");
  253.  
  254. }
  255.  
  256. return noRows;
  257.  
  258. }
  259.  
  260.  
  261.  
  262. /*
  263. * Simple Method to
  264. * handle reading of strings from standard input
  265. * (prints a caption to standard output and reads data from standard input)
  266. */
  267. public static String readFromStdIn(String aCaption) {
  268.  
  269. BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
  270. String inputString;
  271.  
  272. System.out.print(aCaption + ": ");
  273.  
  274. try {
  275.  
  276. inputString = stdIn.readLine();
  277.  
  278. }
  279.  
  280. catch (Exception e){
  281.  
  282. System.out.println();
  283. System.out.println("Error: " + e.getMessage());
  284. System.out.println();
  285.  
  286. return null;
  287.  
  288. }
  289.  
  290. return inputString;
  291.  
  292. }
  293.  
  294.  
  295.  
  296. /*
  297. * Simple Method to
  298. * handle reading of integer values from standard input
  299. * (prints a caption to standard output and reads data from standard input)
  300. */
  301. public static int readIntFromStdIn(String aCaption) {
  302.  
  303. while(true) {
  304.  
  305. String inputString = readFromStdIn(aCaption);
  306.  
  307. try {
  308.  
  309. return Integer.parseInt(inputString);
  310.  
  311. }
  312.  
  313. catch (Exception e) {
  314.  
  315. System.out.println();
  316. System.out.println("Error: " + e.getMessage());
  317. System.out.println("Please provide a correct integer value!");
  318. System.out.println();
  319.  
  320. }
  321.  
  322. }
  323.  
  324. }
  325.  
  326.  
  327.  
  328. /*
  329. * Simple Method to
  330. * handle reading of date values from standard input
  331. * (prints a caption to standard output and reads data from standard input)
  332. */
  333. public static String readDateFromStdIn(String aCaption) {
  334.  
  335. while(true) {
  336.  
  337. String inputString = readFromStdIn(aCaption);
  338.  
  339. try {
  340.  
  341. //validate if input string represents a valid/correct date value/format
  342. //date format is adjusted to 'dd.MM.yyyy', e.g., '24.12.1928'
  343. validateDateString(inputString,"dd.MM.yyyy");
  344.  
  345. return inputString;
  346.  
  347. }
  348.  
  349. catch (Exception e) {
  350.  
  351. System.out.println();
  352. System.out.println("Error: " + e.getMessage());
  353. System.out.println("Please provide a correct date value!");
  354. System.out.println();
  355.  
  356. }
  357.  
  358. }
  359.  
  360. }
  361.  
  362.  
  363.  
  364. /*
  365. * Print debug information (followed by newline) to standard output
  366. * if debug mode is activated (debug flag == true)
  367. */
  368. public static void printlnDebugInfo(String aDebugInfo) {
  369.  
  370. if (DEBUG) {
  371. System.out.println(">>>DEBUG INFO: " + aDebugInfo);
  372. }
  373.  
  374. }
  375.  
  376.  
  377.  
  378. /*
  379. * Print debug information to standard output
  380. * if debug mode is activated (debug flag == true)
  381. */
  382. public static void printDebugInfo(String aDebugInfo) {
  383.  
  384. if (DEBUG) {
  385. System.out.print(">>>DEBUG INFO: " + aDebugInfo);
  386. }
  387.  
  388. }
  389.  
  390.  
  391.  
  392. /*
  393. * Print newline to standard output
  394. * if debug mode is activated (debug flag == true)
  395. *
  396. */
  397. public static void printlnDebugInfo() {
  398.  
  399. if (DEBUG) {
  400. System.out.println();
  401. }
  402.  
  403. }
  404.  
  405.  
  406.  
  407. /*
  408. * *Simple* method to validate if the given date string represents a
  409. * a valid/correct date value/format with respect the given date format string
  410. *
  411. * Note: works in a lot of cases; not proven that it works in all cases
  412. */
  413. public static Date validateDateString(String aDateString, String aDateFormatString) throws ParseException {
  414.  
  415. SimpleDateFormat sdf = new SimpleDateFormat(aDateFormatString);
  416.  
  417. //use strict parsing instead of lenient parsing: with strict parsing,
  418. //the date string must match the (simple date format) object's format
  419. sdf.setLenient(false);
  420.  
  421. try {
  422.  
  423. java.util.Date aDate = sdf.parse(aDateString);
  424.  
  425. //printlnDebugInfo("Date string is: "+ aDateString);
  426. //printlnDebugInfo("Date after parsing is: "+ aDate);
  427. //printlnDebugInfo("Parsed date after formatting is: "+ sdf.format(aDate));
  428. //printlnDebugInfo("Date string cut is: "+ aDateString.substring(0,Math.min(aDateString.length(),10)));
  429.  
  430. //cross check if parsed date's string representation is equal to the given date string
  431. if (sdf.format(aDate).equals(aDateString.substring(0,Math.min(aDateString.length(),10)))) {
  432.  
  433. return aDate;
  434.  
  435. } else {
  436.  
  437. throw new ParseException("Incorrect date (format is '" + aDateFormatString + "'): " + "\"" + aDateString + "\"", 0);
  438.  
  439. }
  440.  
  441. }
  442.  
  443. catch (ParseException pe) {
  444.  
  445. throw new ParseException("Incorrect date (format is '" + aDateFormatString + "'): " + "\"" + aDateString + "\"", 0);
  446.  
  447. }
  448.  
  449.  
  450. }
  451.  
  452.  
  453.  
  454.  
  455. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement