"DRP" Import Database with dom4j complete XML file

Source: Internet
Author: User
Tags xpath import database


XML files play an important role in today's web development, from the database connection configuration to the settings of various other parameters, XML files in the application of reflection technology is very important, but also because the XML file is stored in such a significant parameter, so the read and write operations on the XML file is more important. Let's focus on the DOM4J complete XML file Import database.

0. The XML file with read is as follows:


1. Import SQL scripts with PL Build an Oracle database table (table T_xml ) Structure To receive the XML import data

2, follow, set up the directory and import the corresponding files

Through the introduction of the relevant jar package, the implementation of DOM4J technology parsing XML files (Dom4j-1.6.1.jar,jaxen-1.1-beta-6.jar and other jar packages).


2.1. Introduce the files in Lib into classpath

Test_xmlimport Right-click properties--Java Build path--libraries--add External JARs


2.2. The Dbutil.java contains:

XML configuration file. The driver name is set in the configuration file, providing the URL of the service, user name, user password, etc.

Database connection, shutdown

Transaction commit, Rollback, reset

Package Com.bjpowernode.xml;import Java.sql.connection;import Java.sql.drivermanager;import Java.sql.preparedstatement;import java.sql.resultset;import Java.sql.sqlexception;import java.sql.Statement;/** * Encapsulate Data Common operation * @author Administrator * */public class Dbutil {/** * get Connection * @return */public static Connection Getconne Ction () {Connection conn = null;try {////Register drive class.forname ("Oracle.jdbc.driver.OracleDriver");////connection string (protocol name: JDBC, Sub protocol name: Oracle:thin child Name: @localhost: 1521:oracledb) String url = "Jdbc:oracle:thin: @localhost: 1521:bjpowern"; String username = "DRP1"; String password = "DRP1";////get Link conn = drivermanager.getconnection (URL, username, password);} catch (ClassNotFoundException e) {e.printstacktrace ();} catch (SQLException e) {e.printstacktrace ();} Return conn;} Close database connection public static void Close (Connection conn) {if (conn! = null) {try {conn.close ();} catch (SQLException e) {E.print StackTrace ();}}} Close preparedstatementpublic static void Close (Statement pstmt) {if (pstmt! = null){try {pstmt.close ();} catch (SQLException e) {e.printstacktrace ()}}} Close database connection public static void Close (ResultSet rs) {if (rs! = null) {try {rs.close ();} catch (SQLException e) {e.printstackt Race ();}}} Before the transaction starts, set to manually commit public static void BeginTransaction (Connection conn) {try {if (conn! = null) {if (Conn.getautocommit ( ) {Conn.setautocommit (false);///Manual Commit}}}catch (SQLException e) {}}//COMMIT transaction public static void CommitTransaction ( Connection conn) {try {if (conn! = null) {if (!conn.getautocommit ()) {Conn.commit ();}}} catch (SQLException e) {}}//rollback transaction public static void RollbackTransaction (Connection conn) {try {if (conn! = null) {if (!conn. Getautocommit ()) {Conn.rollback ();}}} catch (SQLException e) {}}//Resets the database connection, reverts to the original state public static void Resetconnection (Connection conn) {try {if (conn! = null) {if (Conn.getautocommit ()) {Conn.setautocommit (false);} else {Conn.setautocommit (true);}}} catch (SQLException e) {}}public static void main (string[] args) {System.out.println (dbutil.getconnection ());}}

2.3. The Testxmlimport class is used to read the information in the XML file and write it to the database table

Package Com.bjpowernode.xml;import Java.io.file;import Java.sql.connection;import java.sql.PreparedStatement; Import Java.sql.resultset;import java.util.iterator;import Java.util.list;import Org.dom4j.document;import Org.dom4j.element;import Org.dom4j.io.saxreader;public class Testxmlimport {/** * @param args */public static void main (S  Tring[] args) {//SQL statement to import data in database table t_xml String sql = "INSERT into T_xml (NUMERO, reposicion, Nombre, Turnos) VALUES (?,?,?, ?)"; Connection conn = null; PreparedStatement pstmt = null;try {conn = dbutil.getconnection ();p stmt = conn.preparestatement (sql);// Locate the XML file that needs to be read document doc = new Saxreader (). Read (New file ("d:/share/javaprojects/drp/test_xmlimport/xml/test01"). XML ");//Extract the contents of the specified node in the XML file list itemList = Doc.selectnodes ("/accesos/item/socio "); for (Iterator Iter=itemlist.iterator (); Iter.hasnext ();) {element el = (Element) Iter.next (); String numero = el.elementtext ("numero"); String reposicion = El.elementtext ("reposicion"); String nombre = El.elementtext ("NombRE "); List turnoslist = el.elements ("Turnos"); StringBuffer sbstring = new StringBuffer (); for (Iterator Iter1=turnoslist.iterator (); Iter1.hasnext ();) {element Turnoselt = (Element) Iter1.next (); String lu = Turnoselt.elementtext ("Lu"); String ma = turnoselt.elementtext ("Ma"); String mi = turnoselt.elementtext ("Mi"); String Ju = Turnoselt.elementtext ("Ju"); String VI = turnoselt.elementtext ("VI"); String sa = turnoselt.elementtext ("sa");  String doo = Turnoselt.elementtext ("Do"), Sbstring.append (Lu + "," + Ma + "," + mi + "," + Ju + "," + VI + "," + sa + "," + doo);} Pstmt.setstring (1, numero);p stmt.setstring (2, reposicion);p stmt.setstring (3, Nombre);p stmt.setstring (4, Sbstring.tostring ());//Add this execution statement to the PreparedStatement object's Batch command  pstmt.addbatch ();} All commands added to the batch command are submitted to the database one at a time to execute Pstmt.executebatch (); System.out.println ("Import XML to database successfully!") ");} catch (Exception e) {e.printstacktrace ();} finally {Dbutil.close (pstmt);D butil.close (conn);}}

Discussion area:

(1) XPath is the XML Path language, which is a language used to determine the location of a part of an XML document. XPath is an XML-based tree structure that provides the ability to find nodes in a data structure tree.
The role of XPath is very similar to what we commonly use in SQL statements, except that SQL is for database operations, and XPath is primarily for querying the XML file.

(2) dom4j is an API for reading and writing XML.
(3) before writing to the database using executeupdate () , and in this article we use addbatch (), what is the difference between them?

pstmt.addbatch () loads several SQL statements together and then sends them to the database execution at a time. Execution takes a short time.
Pstmt.executeupdate () is a single piece that is sent to the database for execution. Time is consumed on the transfer of the database connection.

because the processing speed of the database is very alarming. The single throughput is very high and the execution is extremely efficient. the greater the amount of data, the more the advantages of the former can be realized.


This article describes a common knowledge point:dom4j Complete the XML file import database. At the end of the article, we briefly introduce some XPath and dom4j functions. The difference between Addbatch () and executeupdate () was compared. Hope to bring you some help.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.