Home Database Mysql Tutorial 使用XML封装数据库操作语句的实现_MySQL

使用XML封装数据库操作语句的实现_MySQL

Jun 01, 2016 pm 02:05 PM
name use accomplish operate database statement

在项目开发的过程当中,项目组开发成员的编程风格差异和数据库操作语句SQL的灵活性给项目组带来了越来越多的操作和维护难度。
比如:从user表中取出所有数据,有的人会写成“select * from user”,有的人会写成“select all from user”,虽然在操作中不会有任何的错误,但在其他人读程序的过程时就会产生不好的感觉。
如果这种程序差异在项目中的数量级很多,那么在开发的过程当中程序就会出现各种各样的风格,在维护的过程中就会拼命的挠头并诅咒那些当初写程序的人。

为了整篇文章的举例,现在我们在数据库中建立如下表
TBL_USER
USERID BIGINT
USERNAME VARCHAR(20)
PASSWORD VARCHAR(20)
CREATETIME DATE

TBL_USER_INFO
USERID BIGINT
EMAIL VARCHAR(64)
MOBILE VARCHAR(13)

一、分析

A、分析select语句

于是使用XML来封装数据库操作语句成为项目规范化操作的第一步骤。在这个步骤中,我们将举几个例子来逐步实现封装的目的。
比如 “ SELECT USERNAME, PASSWORD FROM TBL_USER ” 这个语句,分析成XML文件时可以有各种各样的写法,我们现在使用如下的表达方式:
分析(1)
1
2
3
4
5

6

在第一行的句子中使用 dbtrans 为节点名称,
属性name为这个交易的名称,这里为“selectUser”,
属性table为索取表的名称,这里为“TBL_USER”,
属性method为操作数据库的方法,这里为“select”,
子节点意思为从数据库读取数据。
子节点为读取的数据库字段,其中:
属性name为字段的名字,
属性type 为字段的类型,这里设置类型在后面的程序中可以体现出来。

对于“SELECT USERNAME, PASSWORD FROM TBL_USER WHERE USERID=123”语句,我们根据上述的分析,则可将XML描绘为:
分析(2)
1.
2.
3
4

5
6
7
8

9

如果使用的是like操作,我们可以将第3句描述成为

对于“SELECT USERNAME, PASSWORD FROM TBL_USER ORDER BY USERNAME DESC”这个语句,XML如下分析:
分析(3)
1.
2
3
4
5

6
7

这样的语句分析基本上可以完成了绝大部分的普通数据库的select语句的操作,但是毕竟还是会有一些我们无法预料的数据库操作语句会出现,比如
“SELECT USERNAME, PASSWORD FROM TBL_USER WHERE CREATETIME >‘2003-7-16’ AND CREATETIME之中,这时我们可以将XML描绘成为:

”>

但即使使用了以上的变通方法,还是会有很多的特殊语句是无法完成的,比如 “ SELECT COUNT(*) FROM TBL_USER ”, 这时的操作会出现使用XML语句无法描绘的时候,这个时候我们就可以引入了special这个属性,例如:
分析(4)
1
2

这个属性的意思是将所有的特殊交易都特殊表现出来。

B、分析INSERT语句

INSERT 语句在关系型数据库中操作可以说是最麻烦的一条语句了,因为如果你需要在TBL_USER和TBL_USER_INFO表中建立一条对应的数据时,你需要知道插入数据库的主键的值,在JDBC3.0中可以使用Statement.RETURN_GENERATED_KEYS来获取,但是如果为了兼容性考虑,我们在操作过程之中决定采用另一种办法来实现。
我们在数据库中建立一个表,名为:TSYS_PRIMARYKEY,其中包括三个字段,如下:
TSYS_PRIMARYKEY
KEYID BIGINT
TABLENAME VARCHAR(64)
PRIMARYKEY VARCHAR(30)
其中TABLENAME保存表名,PRIMARYKEY保存主键的名称,KEYID保存主键的值,这样的做法目的是在insert语句操作前,先取到现在主键的值,并将该值加1,成为现有的主键,然后进行insert操作,操作完成之后我们还需要update一下TSYS_PRIMARYKEY这个表,确保数据的同步。
现在我们开始分析 INSERT语句了,
INSERT INTO TBL_USER ( USERID, USERNAME, PASSWORD ) VALUES ( 100, ‘test’, ‘test’ )
INSERT INTO TBL_USER_INFO ( USERID, EMAIL, MOBILE ) VALUES ( 100, ‘test@test.com’, ‘1234567890’ )

描绘为XML文件时我们可以描绘如下
分析5)
1.
2
3
4
5
6

7

以及
1
2
3
4
5
6

7

C、分析DELETE语句

Delete语句最常用的可以分为两种,一种是按照键值删除,一种是全部删除,为此我们将此操作划分为两种类型,delete和clear
对于delete类型,举例为:
DELETE FROM TBL_USER_INFO WHERE USERID=123
描述为:
分析(6)
1
2
3
4

5

对于clear类型,举例为:
DELETE FROM TBL_USER_INFO
描述为:
分析(7)
1
2

D、分析UPDATE语句

从update通常的操作我们可以知道使用XML描述时将会出现两种tag,包括,比如:
UPDATE TBL_USER_INFO SET EMAIL=’aaa@aaa.com’ WHERE USERID=123
描述称XML为:
分析8)
1.
2
3
4

5
6
7

8

二、程序设计

好的,在分析了XML文件之后需要我们进入到程序的设计上来了。从以上实现的分析我们可以清楚的看到要实现以上操作,我们必须要做到以下几步:
1 读取XML文件
2 定位相应的交易节点
3 拼SQL 语句
4 数据库操作
5 取数据
6 返回数据

其中针对第一步的读取文件,我们可以封装所有的XML parse语句以及前期的操作封装进入一个类之中,这里我们命名为 XMLLoadFile。

交易处理的过程包括2,5,6三个步骤,可以封装成XMLTransaction类中。当然返回数据这个操作可以单独抽出来作为一个相应的返回类,如果这样是为了在返回的数据报文做处理,比如可以返回XML,Vector或者Hashtable或Map等。这里暂定返回数据为Vector类型,所以将第6步封装进来。

拼装SQL语句,独立建立一个类(XMLCombine),当然也可以分为多个,比如SelectCombine,insertCombine等,这里我们进行统一封装。

数据库操作单独封装成一个类,XMLExecuteSQL。

以上所有的类统一了一个出口类,这里为XMLUtils。这个类提供的几个方法为外部数据操作的主要方法,比如select, insert, delete, update等,还有提供外部程序存取数据的几个方法,比如:setTransNode(设置交易节点),setTransValue(设置交易数据值), setTransKeyValue(设置交易键值数据值)

三、外部程序调用

对于select语句,分析(1)所需编写的程序如下
XMLUtils util = new XMLUtils();
util.setTransNode(“selectUser”);
Vector vRtn = util.select( con );

分析(2)为
XMLUtils util = new XMLUtils();
util.setTransNode(“selectUserByKey”);
util.setTransKeyValue(“userid”, 123 );
Vector vRtn = util.select( con );

对于insert语句,分析(5)程序如下
XMLUtils util = new XMLUtils();
util.setTransNode(“insertUser”);
util.setTransValue(“username”, “test” );
util.setTransValue(“password”, “test” );
Vector vRtn = util.insert( con ); //假设操作成功
long userid = ((Long)((Hashtable)vRtn.elementAt(0)).get(“userid”)).longValue();

util.setTransNode(“insertUserInfo”);
util.setTransValue(“userid”, userid );
util.setTransValue(“email”, “test@test.com” );
util.setTransValue(“mobile”, “1234567890” );
Vector vRtn = util.insert( con );

对于 delete语句 分析( 6)程序如下
XMLUtils util = new XMLUtils();
util.setTransNode(“deleteUser”);
util.setTransKeyValue(“userid”, 100);
util.delete( con );

对于update语句,分析( 8)程序如下
XMLUtils util = new XMLUtils();
util.setTransNode(“updateUserInfo”);
util.setTransKeyValue(“userid”, 123);
util.setTransValue(“email”, “aaa@aaa.com”);
util.update( con );

大家在看这些SQL的操作时,是不是觉得很工整,也很舒服呢?这样做的好处很多,程序员可以不必太多的去拼写SQL 语句,封装的操作可以使所有程序员的程序都可以写的很工整,并有统一的风格。


Keli thisishnh@163.com


word文档放置于此 http://keli.nease.net/XMLDB.doc

最新jar包放置于 http://keli.nease.net/iartbean/iartbean.jar

Sample 放置于 http://keli.nease.net/iartbean/Sample.java
import com.iart.DataBase.XMLControl.*;
import com.microsoft.*;
import java.sql.*;
import java.util.*;
public class Sample{

public static void main( String[] args ){

XMLUtils util = new XMLUtils();
Connection con = null;
try{
System.out.println("[StartupServlet]begin ==============================================");
util.StartupServlet();
System.out.println("[StartupServlet]end ==============================================");
con = getConnection();
System.out.println("[GetConnection]" con.toString() );
//
/* util.setTransNode( "clear" );
util.clear(con);

util.setTransNode( "setpassbyname" );
util.setTransValue( "logonname", "keli2" );
util.setTransValue( "username", "keli3" );
util.setTransValue( "password", "hnh3" );
util.insert(con);
*/

util.setTransNode("backemail","selectRespCode");
//util.setTransKeyValue( "starttime","2003-08-22 00:00:00.0" );
//util.setTransKeyValue( "endtime","2003-08-22 23:59:59.0" );
//util.setTransKeyValue( "docstatusid","2" );

//util.setTransValue( "createtime","CURRENT_TIMESTAMP" );



/* util.setTransNode("insertDocument");
util.setTransValue( "doctypeid", "2");
util.setTransValue( "docstatusid", "1" );

Vector vRtn = util.insert(con);
*/
Hashtable vRtn = util.select(con, 0, -1 );
System.out.println(vRtn.toString());
System.out.println(((Vector)vRtn.get("DATA")).size());

util.setTransNode("backemail","selectRespCode");
vRtn = util.select(con, 2, 20 );
System.out.println(vRtn.toString());
System.out.println(((Vector)vRtn.get("DATA")).size());

vRtn = util.select(con,3, 20 );
System.out.println(vRtn.toString());
System.out.println(((Vector)vRtn.get("DATA")).size());
/* util.setTransNode("selectmaxdoc");
Vector vResult = util.select(con);
Long docid = (Long)((Hashtable)vResult.elementAt(0)).get("docid");

util.setTransNode("insertEmail");
util.setTransValue( "mid", docid.toString());
util.setTransValue( "subject", "test" );
util.setTransValue( "targetaddr", "test@test.com" );
util.setTransValue( "sourceaddr", "test@test.com" );
util.setTransValue( "content", "test@test.com" );

util.insert(con);


util.setTransNode("selectemail");
Vector vResult1 = util.select(con);

for( int i=0; i {
Hashtable vColumn = (Hashtable)vResult1.elementAt(i);
if( vColumn != null )
System.out.println("1" vColumn.toString() );
}

*/

/* util.setTransNode( "deletebyname" );
util.setTransKeyValue("logonname", "keli");
util.delete(con);

util.setTransNode("getpassbyname");
util.setTransKeyValue( "logonname", "%keli%" );
Vector vResult2 = util.select(con);

for( int i=0; i {
Hashtable vColumn = (Hashtable)vResult2.elementAt(i);
if( vColumn != null )
System.out.println(vColumn.toString() );
}
*/
}catch( Exception ex )
{
ex.printStackTrace();
}finally{
try{
con.close();
}catch(Exception ex1)
{
System.out.println(ex1.getMessage());
}
}

}

public static Connection getConnection() throws Exception{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
String strCon = "jdbc:microsoft:sqlserver://localhost:1433;User=nlc;Password=nlc;DatabaseName=nlc";
Connection conn = DriverManager.getConnection(strCon);
return conn;
}

http://keli.nease.net/XMLDB.doc

最新jar包放置于 http://keli.nease.net/iartbean/iartbean.jar

Sample 放置于 http://keli.nease.net/iartbean/Sample.java
import com.iart.DataBase.XMLControl.*;
import com.microsoft.*;
import java.sql.*;
import java.util.*;
public class Sample{

public static void main( String[] args ){

XMLUtils util = new XMLUtils();
Connection con = null;
try{
System.out.println("[StartupServlet]begin ==============================================");
util.StartupServlet();
System.out.println("[StartupServlet]end ==============================================");
con = getConnection();
System.out.println("[GetConnection]" con.toString() );
//
/* util.setTransNode( "clear" );
util.clear(con);

util.setTransNode( "setpassbyname" );
util.setTransValue( "logonname", "keli2" );
util.setTransValue( "username", "keli3" );
util.setTransValue( "password", "hnh3" );
util.insert(con);
*/

util.setTransNode("backemail","selectRespCode");
//util.setTransKeyValue( "starttime","2003-08-22 00:00:00.0" );
//util.setTransKeyValue( "endtime","2003-08-22 23:59:59.0" );
//util.setTransKeyValue( "docstatusid","2" );

//util.setTransValue( "createtime","CURRENT_TIMESTAMP" );



/* util.setTransNode("insertDocument");
util.setTransValue( "doctypeid", "2");
util.setTransValue( "docstatusid", "1" );

Vector vRtn = util.insert(con);
*/
Hashtable vRtn = util.select(con, 0, -1 );
System.out.println(vRtn.toString());
System.out.println(((Vector)vRtn.get("DATA")).size());

util.setTransNode("backemail","selectRespCode");
vRtn = util.select(con, 2, 20 );
System.out.println(vRtn.toString());
System.out.println(((Vector)vRtn.get("DATA")).size());

vRtn = util.select(con,3, 20 );
System.out.println(vRtn.toString());
System.out.println(((Vector)vRtn.get("DATA")).size());
/* util.setTransNode("selectmaxdoc");
Vector vResult = util.select(con);
Long docid = (Long)((Hashtable)vResult.elementAt(0)).get("docid");

util.setTransNode("insertEmail");
util.setTransValue( "mid", docid.toString());
util.setTransValue( "subject", "test" );
util.setTransValue( "targetaddr", "test@test.com" );
util.setTransValue( "sourceaddr", "test@test.com" );
util.setTransValue( "content", "test@test.com" );

util.insert(con);


util.setTransNode("selectemail");
Vector vResult1 = util.select(con);

for( int i=0; i {
Hashtable vColumn = (Hashtable)vResult1.elementAt(i);
if( vColumn != null )
System.out.println("1" vColumn.toString() );
}

*/

/* util.setTransNode( "deletebyname" );
util.setTransKeyValue("logonname", "keli");
util.delete(con);

util.setTransNode("getpassbyname");
util.setTransKeyValue( "logonname", "%keli%" );
Vector vResult2 = util.select(con);

for( int i=0; i {
Hashtable vColumn = (Hashtable)vResult2.elementAt(i);
if( vColumn != null )
System.out.println(vColumn.toString() );
}
*/
}catch( Exception ex )
{
ex.printStackTrace();
}finally{
try{
con.close();
}catch(Exception ex1)
{
System.out.println(ex1.getMessage());
}
}

}

public static Connection getConnection() throws Exception{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
String strCon = "jdbc:microsoft:sqlserver://localhost:1433;User=nlc;Password=nlc;DatabaseName=nlc";
Connection conn = DriverManager.getConnection(strCon);
return conn;
}
}

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

How to use Xiaomi Auto app How to use Xiaomi Auto app Apr 01, 2024 pm 09:19 PM

Xiaomi car software provides remote car control functions, allowing users to remotely control the vehicle through mobile phones or computers, such as opening and closing the vehicle's doors and windows, starting the engine, controlling the vehicle's air conditioner and audio, etc. The following is the use and content of this software, let's learn about it together . Comprehensive list of Xiaomi Auto app functions and usage methods 1. The Xiaomi Auto app was launched on the Apple AppStore on March 25, and can now be downloaded from the app store on Android phones; Car purchase: Learn about the core highlights and technical parameters of Xiaomi Auto, and make an appointment for a test drive. Configure and order your Xiaomi car, and support online processing of car pickup to-do items. 3. Community: Understand Xiaomi Auto brand information, exchange car experience, and share wonderful car life; 4. Car control: The mobile phone is the remote control, remote control, real-time security, easy

How does Hibernate implement polymorphic mapping? How does Hibernate implement polymorphic mapping? Apr 17, 2024 pm 12:09 PM

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.

iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

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

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

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())

An in-depth analysis of how HTML reads the database An in-depth analysis of how HTML reads the database Apr 09, 2024 pm 12:36 PM

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.

How to handle database connection errors in PHP How to handle database connection errors in PHP Jun 05, 2024 pm 02:16 PM

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

How to use spaces correctly in Go How to use spaces correctly in Go Mar 29, 2024 pm 03:42 PM

Go language is a simple, efficient, and highly concurrency programming language. It is an open source language developed by Google. In the Go language, the use of spaces is very important, it can improve the readability and maintainability of the code. This article will introduce how to use spaces correctly in Go language and provide specific code examples. Why you need to use spaces correctly In the programming process, the use of spaces is very important for the readability and beauty of the code. Appropriate use of spaces can make code clearer and easier to read, thus reducing

See all articles