search
HomeDatabaseMysql Tutorial【DRP】采用dom4j完成XML文件导入数据库

xml文件在现在的web开发中扮演着重要的角色,从数据库连接配置到其他各种参数的设置,xml文件在反射技术的应用中举足轻重,也正因为xml文件中保存着如此重要的参数,所以对xml文件的读写操作就显得更加重要。下面我们重点讲解一下dom4j完成XML文件导入数据库


    xml文件在现在的web开发中扮演着重要的角色,从数据库连接配置到其他各种参数的设置,xml文件在反射技术的应用中举足轻重,也正因为xml文件中保存着如此重要的参数,所以对xml文件的读写操作就显得更加重要。下面我们重点讲解一下dom4j完成XML文件导入数据库。

0、带读取的xml文件如下:

【DRP】采用dom4j完成XML文件导入数据库

1、利用PL/SQL导入SQL脚本,建立Oracle数据库表(表T_XML)结构,用于接收xml导入的数据

【DRP】采用dom4j完成XML文件导入数据库

【DRP】采用dom4j完成XML文件导入数据库

2、按照下图,建立目录并导入相应文件

通过引入的相关jar包,实现dom4j技术解析xml文件(dom4j-1.6.1.jar,jaxen-1.1-Beta-6.jar等jar包)。

【DRP】采用dom4j完成XML文件导入数据库

2.1、把lib中的文件引入到classpath中

    test_xmlImport右键properties-- Java Build Path--Libraries--Add External  JARs

【DRP】采用dom4j完成XML文件导入数据库


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() 的区别。希望能为您带来一些帮助。



Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
MySQL BLOB : are there any limits?MySQL BLOB : are there any limits?May 08, 2025 am 12:22 AM

MySQLBLOBshavelimits:TINYBLOB(255bytes),BLOB(65,535bytes),MEDIUMBLOB(16,777,215bytes),andLONGBLOB(4,294,967,295bytes).TouseBLOBseffectively:1)ConsiderperformanceimpactsandstorelargeBLOBsexternally;2)Managebackupsandreplicationcarefully;3)Usepathsinst

MySQL : What are the best tools to automate users creation?MySQL : What are the best tools to automate users creation?May 08, 2025 am 12:22 AM

The best tools and technologies for automating the creation of users in MySQL include: 1. MySQLWorkbench, suitable for small to medium-sized environments, easy to use but high resource consumption; 2. Ansible, suitable for multi-server environments, simple but steep learning curve; 3. Custom Python scripts, flexible but need to ensure script security; 4. Puppet and Chef, suitable for large-scale environments, complex but scalable. Scale, learning curve and integration needs should be considered when choosing.

MySQL: Can I search inside a blob?MySQL: Can I search inside a blob?May 08, 2025 am 12:20 AM

Yes,youcansearchinsideaBLOBinMySQLusingspecifictechniques.1)ConverttheBLOBtoaUTF-8stringwithCONVERTfunctionandsearchusingLIKE.2)ForcompressedBLOBs,useUNCOMPRESSbeforeconversion.3)Considerperformanceimpactsanddataencoding.4)Forcomplexdata,externalproc

MySQL String Data Types: A Comprehensive GuideMySQL String Data Types: A Comprehensive GuideMay 08, 2025 am 12:14 AM

MySQLoffersvariousstringdatatypes:1)CHARforfixed-lengthstrings,idealforconsistentlengthdatalikecountrycodes;2)VARCHARforvariable-lengthstrings,suitableforfieldslikenames;3)TEXTtypesforlargertext,goodforblogpostsbutcanimpactperformance;4)BINARYandVARB

Mastering MySQL BLOBs: A Step-by-Step TutorialMastering MySQL BLOBs: A Step-by-Step TutorialMay 08, 2025 am 12:01 AM

TomasterMySQLBLOBs,followthesesteps:1)ChoosetheappropriateBLOBtype(TINYBLOB,BLOB,MEDIUMBLOB,LONGBLOB)basedondatasize.2)InsertdatausingLOAD_FILEforefficiency.3)Storefilereferencesinsteadoffilestoimproveperformance.4)UseDUMPFILEtoretrieveandsaveBLOBsco

BLOB Data Type in MySQL: A Detailed Overview for DevelopersBLOB Data Type in MySQL: A Detailed Overview for DevelopersMay 07, 2025 pm 05:41 PM

BlobdatatypesinmysqlareusedforvoringLargebinarydatalikeImagesoraudio.1) Useblobtypes (tinyblobtolongblob) Basedondatasizeneeds. 2) Storeblobsin Perplate Petooptimize Performance.3) ConsidersxterNal Storage Forel Blob Romana DatabasesizerIndimprovebackupupe

How to Add Users to MySQL from the Command LineHow to Add Users to MySQL from the Command LineMay 07, 2025 pm 05:01 PM

ToadduserstoMySQLfromthecommandline,loginasroot,thenuseCREATEUSER'username'@'host'IDENTIFIEDBY'password';tocreateanewuser.GrantpermissionswithGRANTALLPRIVILEGESONdatabase.*TO'username'@'host';anduseFLUSHPRIVILEGES;toapplychanges.Alwaysusestrongpasswo

What Are the Different String Data Types in MySQL? A Detailed OverviewWhat Are the Different String Data Types in MySQL? A Detailed OverviewMay 07, 2025 pm 03:33 PM

MySQLofferseightstringdatatypes:CHAR,VARCHAR,BINARY,VARBINARY,BLOB,TEXT,ENUM,andSET.1)CHARisfixed-length,idealforconsistentdatalikecountrycodes.2)VARCHARisvariable-length,efficientforvaryingdatalikenames.3)BINARYandVARBINARYstorebinarydata,similartoC

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools