【DRP】采用dom4j完成XML文件导入数据库
xml文件在现在的web开发中扮演着重要的角色,从数据库连接配置到其他各种参数的设置,xml文件在反射技术的应用中举足轻重,也正因为xml文件中保存着如此重要的参数,所以对xml文件的读写操作就显得更加重要。下面我们重点讲解一下dom4j完成XML文件导入数据库
xml文件在现在的web开发中扮演着重要的角色,从数据库连接配置到其他各种参数的设置,xml文件在反射技术的应用中举足轻重,也正因为xml文件中保存着如此重要的参数,所以对xml文件的读写操作就显得更加重要。下面我们重点讲解一下dom4j完成XML文件导入数据库。
0、带读取的xml文件如下:
1、利用PL/SQL导入SQL脚本,建立Oracle数据库表(表T_XML)结构,用于接收xml导入的数据
2、按照下图,建立目录并导入相应文件
通过引入的相关jar包,实现dom4j技术解析xml文件(dom4j-1.6.1.jar,jaxen-1.1-Beta-6.jar等jar包)。
2.1、把lib中的文件引入到classpath中
test_xmlImport右键properties-- Java Build Path--Libraries--Add External JARs
2.2、DbUtil.java中包含:
xml配置文件。在该配置文件中设置了驱动名称,提供服务的url,用户名以及用户密码等内容
数据库连接、关闭
事务提交、回滚、重置
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; /** * 封装数据常用操作 * @author Administrator * */ public class DbUtil { /** * 取得Connection * @return */ public static Connection getConnection() { Connection conn = null; try { //// 注册驱动 Class.forName("oracle.jdbc.driver.OracleDriver"); //// 连接字符串(协议名:jdbc,子协议名: oracle:thin 子名称:@localhost:1521:oracleDB) String url = "jdbc:oracle:thin:@localhost:1521:bjpowern"; String username = "drp1"; String password = "drp1"; //// 获得链接 conn = DriverManager.getConnection(url, username, password); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return conn; } // 关闭数据库连接 public static void close(Connection conn) { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } //关闭PreparedStatement public static void close(Statement pstmt) { if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } //关闭数据库连接 public static void close(ResultSet rs ) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } //事务开始前的准备工作,设置为手动提交 public static void beginTransaction(Connection conn) { try { if (conn != null) { if (conn.getAutoCommit()) { conn.setAutoCommit(false); //手动提交 } } }catch(SQLException e) {} } //提交事务 public static void commitTransaction(Connection conn) { try { if (conn != null) { if (!conn.getAutoCommit()) { conn.commit(); } } }catch(SQLException e) {} } //回滚事务 public static void rollbackTransaction(Connection conn) { try { if (conn != null) { if (!conn.getAutoCommit()) { conn.rollback(); } } }catch(SQLException e) {} } //重置数据库连接,恢复到原来状态 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、TestXMLImport类用于读取XML文件中的信息,并写入数据库表中
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(String[] args) { //想数据库表T_XML中导入数据的sql语句 String sql = "insert into T_XML(NUMERO, REPOSICION, NOMBRE, TURNOS) values (?, ?, ?, ?)"; Connection conn = null; PreparedStatement pstmt = null; try { conn = DbUtil.getConnection(); pstmt = conn.prepareStatement(sql); //找到需要读取的XML文件的位置 Document doc = new SAXReader().read(new File("D:/share/JavaProjects/drp/test_xmlImport/xml/test01.XML")); // 提取XML文件中指定节点的内容 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); pstmt.setString(2, reposicion); pstmt.setString(3, nombre); pstmt.setString(4, sbString.toString()); //把这条执行语句加到PreparedStatement对象的批处理命令中 pstmt.addBatch(); } //把以上添加到批处理命令中的所有命令一次过提交给数据库来执行 pstmt.executeBatch(); System.out.println("将XML导入数据库成功!"); } catch (Exception e) { e.printStackTrace(); } finally { DbUtil.close(pstmt); DbUtil.close(conn); } } }
讨论区:
(1)XPath即为XML路径语言,它是一种用来确定XML文档中某部分位置的语言。XPath基于XML的树状结构,提供在数据结构树中找寻节点的能力。
XPath的作用与我们所常用的sql语句的作用是十分相似的,只不过sql针对的是数据库操作,而XPath主要是针对xml文件的查询定位用的。
(2)dom4j是用于读写XML的API.
(3)之前在写入数据库的时候采用executeUpdate() ,而本文中我们采用addBatch(),它们之间有什么区别吗?
pstmt.addBatch()把若干sql语句装载到一起,然后一次送到数据库执行。执行需要很短的时间。
pstmt.executeUpdate() 是一条一条发往数据库执行的。时间都消耗在数据库连接的传输上面。
因为数据库的处理速度是非常惊人的。单次吞吐量很大,执行效率极高。在数据量越大的时候,越能体现前者的优势 。
本文介绍了一个常用的知识点:dom4j完成XML文件导入数据库。文章末尾简要介绍了一些XPath、dom4j的作用。并对比了addBatch()与executeUpdate() 的区别。希望能为您带来一些帮助。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Go language is an efficient, concise and easy-to-learn programming language. It is favored by developers because of its advantages in concurrent programming and network programming. In actual development, database operations are an indispensable part. This article will introduce how to use Go language to implement database addition, deletion, modification and query operations. In Go language, we usually use third-party libraries to operate databases, such as commonly used sql packages, gorm, etc. Here we take the sql package as an example to introduce how to implement the addition, deletion, modification and query operations of the database. Assume we are using a MySQL database.

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

Hibernate polymorphic mapping can map inherited classes to the database and provides the following mapping types: joined-subclass: Create a separate table for the subclass, including all columns of the parent class. table-per-class: Create a separate table for subclasses, containing only subclass-specific columns. union-subclass: similar to joined-subclass, but the parent class table unions all subclass columns.

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

The os.Rename function is used in Go language to rename files. The syntax is: funcRename(oldpath,newpathstring)error. This function renames the file specified by oldpath to the file specified by newpath. Examples include simple renaming, moving files to different directories, and ignoring error handling. The Rename function performs an atomic operation and may only update directory entries when the two files are in the same directory. Renames may fail across volumes or while a file is in use.

HTML cannot read the database directly, but it can be achieved through JavaScript and AJAX. The steps include establishing a database connection, sending a query, processing the response, and updating the page. This article provides a practical example of using JavaScript, AJAX and PHP to read data from a MySQL database, showing how to dynamically display query results in an HTML page. This example uses XMLHttpRequest to establish a database connection, send a query and process the response, thereby filling data into page elements and realizing the function of HTML reading the database.

Use PHPXML functions to process XML data: Parse XML data: simplexml_load_file() and simplexml_load_string() load XML files or strings. Access XML data: Use the properties and methods of the SimpleXML object to obtain element names, attribute values, and subelements. Modify XML data: add new elements and attributes using the addChild() and addAttribute() methods. Serialized XML data: The asXML() method converts a SimpleXML object into an XML string. Practical example: parse product feed XML, extract product information, transform and store it into a database.
