Advertisement
Guest User

Untitled

a guest
Apr 1st, 2017
923
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 13.38 KB | None | 0 0
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6.  
  7. package oraclexmltypeexample;
  8.  
  9. import java.io.FileInputStream;
  10. import java.io.FileNotFoundException;
  11. import java.sql.Connection;
  12. import java.sql.DriverManager;
  13. import java.sql.ResultSet;
  14. import java.sql.SQLException;
  15. import java.sql.Statement;
  16. import java.util.Scanner;
  17. import oracle.jdbc.*;
  18. import oracle.xdb.XMLType;
  19.  
  20. /**
  21.  *
  22.  * @author piyush
  23.  */
  24. public class OracleXMLTypeExample {
  25.  
  26.     /**
  27.      * @param args the command line arguments
  28.      */
  29.     public static void main(String[] args) {
  30.         // TODO code application logic here
  31.        
  32.        
  33.               // the following statement loads the Oracle jdbc driver
  34.  
  35.     try {
  36.       Class.forName ("oracle.jdbc.driver.OracleDriver");
  37.     } catch (ClassNotFoundException e) {
  38.         System.out.println ("Could not load the driver");
  39.       }
  40.    
  41.     String user, pass, host, servicename;
  42.    
  43.     Scanner sc = new Scanner(System.in);
  44.     System.out.println("Type userid, password, hostname or ipaddress: ");
  45.     user = sc.next();
  46.     pass = sc.next();
  47.     host = sc.next();
  48.     servicename = "xe";
  49.     System.out.println(user+" "+pass+" "+host);
  50.  
  51.     /*  userid, password and hostname are obtained from the console
  52.      *  It is assumed that the service name is XE and the database server
  53.      *  listens on the default port 1521.
  54.      */
  55.    
  56.     try (                                     //try-with-resources
  57.       Connection conn = DriverManager.getConnection
  58.         ("jdbc:oracle:thin:"+user+"/"+pass+"@"+host+":1521/"+servicename);
  59.       Statement stmt = conn.createStatement();      
  60.     )
  61.     {
  62.    
  63.     /* JDBC default is to commit each SQL statement as it is sent to the database.  Setting autocommmit=false changes the default
  64.        behaviour so that transactions have to be committed explicity.
  65.      */
  66.     conn.setAutoCommit(false);
  67.    
  68.     stmt.executeUpdate("DROP TABLE Addrbook");
  69.  
  70.     //  ----------------   CREATING A TABLE WITH AN XMLTYPE ATTRIBUTE --------
  71.  
  72.         stmt.executeUpdate("CREATE TABLE Addrbook(name VARCHAR(20) " +
  73.                            "CONSTRAINT Addrbook_PK PRIMARY KEY, " +
  74.                            " card SYS.XMLTYPE, creationdate Date)");
  75.  
  76.     //  --------------  INSERTING XMLType DATA  ----------------------
  77.  
  78.    // We can insert XMLType data by supplying the corresponding string.
  79.  
  80.    stmt.executeUpdate("INSERT INTO Addrbook VALUES( " +
  81.                        " 'John', " +
  82.                        "    " +
  83.                        " sys.XMLType.createXML(" +
  84.                         " '<ACARD CREATEDBY=\"Thomas\"> \n " +
  85.                           " <EMAIL> john1234@yahoo.co.uk </EMAIL> \n "  +
  86.                           " <HOMEPHONE>90361111</HOMEPHONE> \n " +
  87.                           " <WORKPHONE>90362222</WORKPHONE> \n " +
  88.                           " <ADDRESS> \n " +
  89.                             " <STREET> 10 Shore Road </STREET> \n " +
  90.                             " <CITY> Newtownabbet </CITY> \n " +
  91.                            " <POSTCODE> BT37 0QB </POSTCODE> \n " +
  92.                          " </ADDRESS> \n " +
  93.                          " <COMMENT> PGD/ M Sc Informatics Student </COMMENT> \n " +
  94.                         "</ACARD>'), " +
  95.                         "           " +
  96.                         " DATE'2007-04-17' " +
  97.                                                " )")   ;
  98.  
  99.     /*  The following is a somewhat convoluted way of reading XML data from a file.
  100.     We open a FileInputStream and use a constructor for XMLType to read the data
  101.     into an instance of XMLType.  However when we pass it to SQL, we convert it
  102.     to a string.
  103.  
  104.     Note that sys.XMLType in the SQL statement is a PL/SQL package ! (Not Java!)
  105.  
  106.     We are converting a Java XMLType into a String and then into a PL/SQL XMLType.
  107.     */
  108.  
  109.     FileInputStream fis = new FileInputStream("xmltypedata/acard1.xml");
  110.     XMLType xmlv = new XMLType(conn, fis);
  111.     System.out.println(xmlv.getStringVal());
  112.  
  113.     stmt.executeUpdate("INSERT INTO Addrbook VALUES( 'Tom', " +
  114.                        "sys.XMLType.createXML( ' " +  xmlv.getStringVal() + " ' ), " +
  115.                        "DATE'2007-04-18')" );
  116.  
  117.  
  118.     /*  The following code is a lot neater.  Note that we have to use
  119.     OraclePreparedStatement rather than JDBC PreparedStatement because
  120.     the latter knows nothing about XMLType.
  121.     */
  122.  
  123.     // First read the data from file into an instance of XMLType.
  124.  
  125.     FileInputStream fis2 = new FileInputStream("xmltypedata/acard2.xml");
  126.     XMLType xmlv2 = new XMLType(conn, fis2);
  127.  
  128.     String sqltxt = "INSERT INTO Addrbook VALUES(?, ?, ?)";
  129.  
  130.     OraclePreparedStatement osqlstmt = (OraclePreparedStatement) conn.prepareStatement(sqltxt);
  131.     osqlstmt.setString(1, "Gerry");
  132.  
  133.     // The 2nd argument  is of type XMLType
  134.     osqlstmt.setObject(2, xmlv2);
  135.     java.sql.Date when; when = java.sql.Date.valueOf("2007-04-20");
  136.     osqlstmt.setDate(3, when);
  137.     osqlstmt.execute();
  138.  
  139.     // ---------------------  QUERYING  -------------------------------------
  140.  
  141.     // We have 3 rows in the Addrbook table.  Let's query it.
  142.  
  143.     // Let's just retrieve John's ACARD as a Clob and print it.
  144.    ResultSet result = stmt.executeQuery("SELECT a.card.getClobval() " +
  145.                                         "FROM Addrbook a WHERE Name='John'");
  146.    System.out.println("\n Results as Clob: \n");
  147.  
  148.    while(result.next())
  149.       System.out.println(result.getString(1));
  150.  
  151.    //  We could also have retrieved it as a String
  152.    result = stmt.executeQuery("SELECT a.card.getStringval() FROM Addrbook a WHERE Name='Tom'");
  153.    System.out.println("\n Results as String: \n");
  154.  
  155.    while(result.next())
  156.       System.out.println(result.getString(1));
  157.  
  158.  
  159.    //  ------------  QUERYING WITH XPATH EXPRESSIONS -----------------------
  160.  
  161.    /*  An alternative method for retrieving everyone's name and ACARD.
  162.        The extract function (of the PL/SQL XMLType) takes an XPATH expression as an argument and
  163.        returns an XMLType value.  We must convert it to String by using the getStringVal function.
  164.    */
  165.  
  166.  
  167.    result = stmt.executeQuery("SELECT a.name, a.card.extract('/').getStringval() " +
  168.                               "FROM Addrbook a ");
  169.    System.out.println("\n Name and /: \n");
  170.  
  171.    while(result.next())
  172.       System.out.println(result.getString(1) + "  " + result.getString(2) );
  173.  
  174.    // The following SQL does exactly the same thing as the previous statement.
  175.  
  176.    result = stmt.executeQuery("SELECT a.name, a.card.extract('/ACARD').getStringval() " +
  177.                               "FROM Addrbook a ");
  178.    System.out.println("\n Name and /ACARD: \n");
  179.  
  180.    while(result.next())
  181.       System.out.println(result.getString(1) + "  " + result.getString(2) );
  182.  
  183.    //  Let's get everyone's name and e-mail address
  184.  
  185.    result = stmt.executeQuery("SELECT a.name, " +
  186.             "a.card.extract('/ACARD/EMAIL').getStringVal() " +
  187.             "FROM Addrbook a ");
  188.    System.out.println("\n Name and E-mail Address: \n");
  189.  
  190.    while(result.next())
  191.       System.out.println(result.getString(1) + "  " + result.getString(2) );
  192.  
  193.    //Let's get everyone's name and e-mail address WITHOUT the surrounding EMAIL tag
  194.  
  195.    result = stmt.executeQuery("SELECT a.name, " +
  196.             "a.card.extract('/ACARD/EMAIL/text()').getStringVal() " +
  197.             "FROM Addrbook a ");
  198.    System.out.println("\n Name & E-Mail without the EMAIL tag: \n");
  199.  
  200.    while(result.next())
  201.       System.out.println(result.getString(1) + "  " + result.getString(2) );
  202.  
  203.    /* The previous 2 queries did not return Gerry's e-mail address because it is not
  204.       a subelement of /ACARD but of /ACARD/CONTACTS.  If we look through the
  205.       grandchindren of /ACARD, we should find  Gerry's E-mail address. Notice the
  206.       use of the wildcard character * .
  207.    */
  208.  
  209.    result = stmt.executeQuery("SELECT a.name, " +
  210.             "a.card.extract('/ACARD/*/EMAIL/text()').getStringVal() " +
  211.             "FROM Addrbook a ");
  212.    System.out.println("\n Name & E-Mail (only Gerry's): \n");
  213.  
  214.    while(result.next())
  215.       System.out.println(result.getString(1) + "  " + result.getString(2) );
  216.  
  217.  
  218.    /* Alternatively, we can search all descendants of /ACARD (and not just the
  219.       children or grandchildren) by extracting /ACARD//EMAIL.
  220.       Notice the double slash!
  221.    */
  222.  
  223.    result = stmt.executeQuery("SELECT a.name, " +
  224.             "a.card.extract('/ACARD//EMAIL/text()').getStringVal() " +
  225.             "FROM Addrbook a ");
  226.    System.out.println("\n Name & E-Mail (including Gerry's): \n");
  227.  
  228.    while(result.next())
  229.       System.out.println(result.getString(1) + "  " + result.getString(2) );
  230.  
  231.    /* We can use predicates in XPATH expressions.  These are enclosed in [ ]
  232.       The following query retrieves the name and address of the person whose
  233.       e-mail address is john1234@yahoo.co.uk. Watch surrounding spaces though.
  234.    */
  235.  
  236.    result = stmt.executeQuery("SELECT a.name, " +
  237.           "a.card.extract('/ACARD[EMAIL=\" john1234@yahoo.co.uk \"]/ADDRESS').getStringVal() " +
  238.           "FROM Addrbook a ");
  239.    System.out.println("\n Name & Address of a given E-Mail address: \n");
  240.  
  241.    while(result.next())
  242.       System.out.println(result.getString(1) + "  " + result.getString(2) );
  243.  
  244.  
  245.    /* The previous query also returns Tom and Gerry's names, albeit with NULL address.
  246.       We can use the existsNode method to retrieve only those names that match the given
  247.       e-mail address. The existsNode method takes an XPATH expression as an arguments and
  248.       returns 0 or 1.
  249.    */
  250.  
  251.    result = stmt.executeQuery("SELECT a.name, " +
  252.           "a.card.extract('/ACARD[EMAIL=\" john1234@yahoo.co.uk \"]/ADDRESS').getStringVal() "+
  253.           "FROM Addrbook a " +
  254.           "WHERE a.card.existsNode('/ACARD[EMAIL=\" john1234@yahoo.co.uk \"]')=1");
  255.    System.out.println("\n Name & Address of a given E-Mail address: \n");
  256.  
  257.    while(result.next())
  258.       System.out.println(result.getString(1) + "  " + result.getString(2) );
  259.  
  260.    /* The [ ] expression is also used to denote an index in a list.  The following
  261.       query retrieves everyone's second WORKPHONE.
  262.    */
  263.  
  264.    result = stmt.executeQuery("SELECT a.name, " +
  265.             "a.card.extract('/ACARD//WORKPHONE[2]').getStringVal() FROM Addrbook a ");
  266.    System.out.println("\n Name & Second WORKPHONE: \n");
  267.  
  268.    while(result.next())
  269.       System.out.println(result.getString(1) + "  " + result.getString(2) );
  270.  
  271.    /* We don't really want to retrieve the names of those who don't have a 2nd WORKPHONE.
  272.       Therefore use existsNode.
  273.    */
  274.  
  275.    result = stmt.executeQuery("SELECT a.name, " +
  276.             "a.card.extract('/ACARD//WORKPHONE[2]').getStringVal() FROM Addrbook a " +
  277.             "WHERE a.card.existsNode('/ACARD//WORKPHONE[2]')=1" );
  278.    System.out.println("\n Name & Second WORKPHONE: \n");
  279.  
  280.    while(result.next())
  281.       System.out.println(result.getString(1) + "  " + result.getString(2) );
  282.  
  283.  
  284.  
  285.    // So far all queries have used XML elements.  Let us use attributes instead.
  286.    // Name and mobile number of everyone whose ACARD was created by Thomas.
  287.  
  288.    result = stmt.executeQuery("SELECT a.name, " +
  289.             "a.card.extract('/ACARD//MOBILE').getStringVal() FROM Addrbook a " +
  290.             "WHERE a.card.extract('/ACARD/@CREATEDBY').getStringVal() = 'Thomas' ");
  291.    System.out.println("\n Name & Second WORKPHONE: \n");
  292.  
  293.    while(result.next())
  294.       System.out.println(result.getString(1) + "  " + result.getString(2) );
  295.  
  296.  
  297.    // -----------------    FUNCTIONS ----------------------------------------
  298.  
  299.  
  300.    result = stmt.executeQuery("SELECT a.name, " +
  301.                   "a.card.extract('/ACARD[count(//WORKPHONE) = 2]//WORKPHONE[2]').getStringVal() FROM Addrbook a " );
  302.  
  303.    System.out.println("\n Count Function: \n");
  304.  
  305.    while(result.next())
  306.       System.out.println(result.getString(1) + "  " + result.getString(2) );
  307.  
  308.    System.out.println("\n End of printout from Count Function: \n");
  309.  
  310.    result = stmt.executeQuery("SELECT a.name, " +
  311.                   "a.card.extract('/ACARD[count(//WORKPHONE)]').getStringVal() FROM Addrbook a " );
  312.  
  313.    System.out.println("\n Count Function: \n");
  314.  
  315.    while(result.next())
  316.       System.out.println(result.getString(1) + "  " + result.getString(2) );
  317.  
  318.    System.out.println("\n End of printout from Count Function: \n");
  319.  
  320.  
  321.  
  322.    // ------------------   UPDATING THE VALUE OF AN XMLType ATTRIBUTE  -------------------
  323.  
  324.    /*  Standard SQL, e.g.
  325.  
  326.        UPDATE  Addrbook SET card = sys.XMLType.createXML('string-containing-xml-data')
  327.        WHERE name = 'john';
  328.  
  329.        would do this.
  330.    */
  331.  
  332.  
  333.    //  ------------------  DELETING ROWS -------------------------------------------------
  334.  
  335.    //  Let us get rid of everyone whose ACARD was created by Thomas.
  336.  
  337.    stmt.executeUpdate("DELETE Addrbook a " +
  338.                       "WHERE a.card.extract('/ACARD/@CREATEDBY').getStringVal() = 'Thomas' " );
  339.  
  340.    // There should be nothing left. CHECK.
  341.  
  342.    result = stmt.executeQuery("SELECT a.name FROM Addrbook a ");
  343.    System.out.println("\n After deleting all created by Thomas: \n");
  344.    while(result.next())
  345.        System.out.println(result.getString(1));
  346.  
  347.    stmt.close();
  348.    conn.close();
  349.    
  350.    
  351.    
  352.    
  353.    
  354.    
  355.     }
  356.         catch (SQLException | FileNotFoundException exc) {
  357.        
  358.         exc.printStackTrace(System.err);
  359.        
  360.     }
  361.    
  362. }
  363. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement