DOM4J 读取XML配置文件进行数据库连接
介绍介绍DOM4J。 据说是非常优秀非常优秀的Java XML API( Dom4j is an easy to use, open source library for working with XML, XPath and XSLT on the Java platform using the Java Collections Framework and with full support for DOM, SAX and JAXP.
介绍介绍DOM4J。
据说是非常优秀非常优秀的Java XML API(Dom4j is an easy to use, open source library for working with XML, XPath and XSLT on the Java platform using the Java Collections Framework and with full support for DOM, SAX and JAXP.)。
关于XML文件。
A君问了我一个问题,为什么java中XML作为配置文件,为什么不用其他的呢?像text文件等等。
我的第一个反应是,为(喂)什么就吃什么。。。然后再问为什么。。。开始的时候模仿着做,时间长的时候思
考一些经常使用的东西的原因,就像为什么同一个公司,他的职位比我高一样。。。我们需要的是思考和学习。。。
转回来说说我们配置文件的特点:我们在这里的配置文件需要能够存放少量的数据,并易于操作和维护。所以在
开始进行选择的时候就会综合考虑,text的特性,编码问题等等。所以综合考虑的话就会把XML作为j2ee的一个标准
而不是text作为j2ee的标准。(仅是我的理解......)
最开始我们连接数据库的方式:
/** * 取得connection * @return * */ public static Connection getConnection() throws ClassNotFoundException { //数据库连接对象。 Connection conn = null; try { //驱动名称。 Class.forName("oracle.jdbc.driver.OracleDriver"); //数据库连接字符串。 String url = "jdbc:oracle:thin:@localhost:1521:BJPOWERNODE"; //oracle数据库用户名和密码。 String username = "drp"; String password = "drp"; //连接数据库。 conn = DriverManager.getConnection(url, username, password); }catch(ClassNotFoundException e){ //打印错误。 e.printStackTrace(); }catch(SQLException e){ //打印错误。 e.printStackTrace(); } //返回连接对象。 return conn; }
进行了些许的优化:
我们把一些连接数据的配置文件放到XML文件中,很明显,我们这样做的目的,为了改变方便。从变化的角度来
预测问题,所以把最开始的配置数据放到连接数据库类的代码中,抽取出来了,我们放到了配置文件中。
连接的配置信息,我们放到web.xml中。
<?xml version="1.0" encoding="UTF-8"?> <config> <db-info> <driver-name>oracle.jdbc.driver.OracleDriver</driver-name> <url>jdbc:oracle:thin:@localhost:1521:BJPOWERNODE</url> <user-name>drp</user-name> <password>drp</password> </db-info> </config>
这样抽取出来的话,我们要从这个XML文件中读取一些驱动名称,连接字符串,用户名称和密码信息了。
如果我们把读取和连接放到连接这个类(DbUtil数据库操作工具类)中的话,这个类的职责就太重,这样不利于
大型系统的扩展工作。于是,我们把读取配置文件这个工作给了专门的一个类来干这件事情,我们命名他为
XmlConfigReader ,用这个类读取XML文件。
从网上查找关于读取XML文件的文章,源码也很多,据说有四种方式,http://developer.51cto.com/art/201106/270685.htm 在这里就不详细说明了。我们这里采用的是DOM4j的方式来读取XML文件。主要是引入dom4j相应的包和在使用过程中查看dom4j的API就可以喽。
读取配置文件,我们读取的是字符串,驱动名称,连接字符串,用户名称和密码信息,他们是一个整体,我们函
数的返回值如果是字符串的话,再连接数据库的时候还要把这个长长的字符串分开,这样很不方便。于是我们把他们
进行了封装,我们把他们封装成为一个配置的工具类,JdbcConfig,这样我们传递一个整体就可以了。就像人是一个
整体的,我们不要把他的胳膊腿等分开传递。
我们封装的配置文件实体类:
/** * jdbc配置信息。 * @author lovesummer * */ public class JdbcConfig { //连接字符串。 private String url; //用户名。 private String userName; //密码。 private String password; //驱动器的名称。 private String driverName; public String getDriverName() { return driverName; } public void setDriverName(String driverName) { this.driverName = driverName; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } //覆盖object的toString方法。 @Override public String toString() { // TODO Auto-generated method stub return this.getClass().getName() + "{driverName:" + driverName + ", url:" + url + ",userName :" + userName + "}"; } }
我们读取配置文件的类:
package com.bjpowernode.drp.util; import java.io.InputStream; import javax.servlet.jsp.tagext.TryCatchFinally; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; //读取配置文件类。 /** * 采用单例模式解析sys-config.xml文件。 * 解析sys-config.xml文件。 *@author lovesummer * */ public class XmlConfigReader { //勤汉式。 //私有的静态的成员变量。 private static XmlConfigReader instance = new XmlConfigReader(); //保存jdbc相关配置信息对象。 private JdbcConfig jdbcconfig = new JdbcConfig(); //私有的构造方法。 private XmlConfigReader() { SAXReader reader = new SAXReader(); //拿到当前线程。 InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("sys-config.xml"); try { Document doc = reader.read(in); //取得xml中的Element。1 、取出驱动器的名字。 Element driverNameElt = (Element)doc.selectObject("/config/db-info/driver-name"); //2 、取出url字符串。 Element urlElt = (Element)doc.selectObject("/config/db-info/url"); //3、取出用户名称和密码。 Element userNameElt = (Element)doc.selectObject("/config/db-info/user-name"); Element passwordElt = (Element)doc.selectObject("/config/db-info/password"); //取得jdbc相关配置信息。 jdbcconfig.setDriverName(driverNameElt.getStringValue()); jdbcconfig.setUrl(urlElt.getStringValue()); jdbcconfig.setUserName(userNameElt.getStringValue()); jdbcconfig.setPassword(passwordElt.getStringValue()); } catch (DocumentException e) { // 打印错误 e.printStackTrace(); } } //公共的静态的入口方法。 public static XmlConfigReader getInstance() { return instance; } /** * 返回jdbc相关配置。 * @return */ public JdbcConfig getJdbcConfig(){ return jdbcconfig; } }
优化后我们连接数据库的类(就像改革开放前后的中国):
/** * 封装数据库常用操作,工具类 * @author lovesummer * */ public class DbUtil { /** * 取得connection * @return * */ public static Connection getConnection() throws ClassNotFoundException { Connection conn = null; try { //新建jdbc配置类。 JdbcConfig jdbcconfig = XmlConfigReader.getInstance().getJdbcConfig(); //取出驱动器的名字。 Class.forName(jdbcconfig.getDriverName()); //取得连接对象。 conn = DriverManager.getConnection(jdbcconfig.getUrl(), jdbcconfig.getUserName(), jdbcconfig.getPassword()); } catch (ClassNotFoundException e) { // 抛出 exception e.printStackTrace(); }catch(SQLException e) { e.printStackTrace(); } return conn; } //测试。 public static void main(String[] args ) throws ClassNotFoundException{ System.out.println(DbUtil.getConnection()); } }
优化后把每个类的职责都分工明确了,在这基础上还可以再进行优化的。在这里就不讲述了。在这过程中学习到了
代码优化的这种思维方式,装上了程序员的思想,代码就这样一步步有了灵魂........加油.....

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA


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

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

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools