2. 对数据表进行CRUD操作
为了使读者清楚地知道Saxon SQL扩展的使用,本文将使用非常基本的CRUD操作。一但读者掌握这些基本的操作,就完全可以利用本文所讲的XSLT来执行复杂的SQL操作。我们的数据模型是非常简单的,如图1所示:
为了使读者清楚地知道Saxon SQL扩展的使用,本文将使用非常基本的CRUD操作。一但读者掌握这些基本的操作,就完全可以利用本文所讲的XSLT来执行复杂的SQL操作。我们的数据模型是非常简单的,如图1所示:

(1) 插入记录
下面让我们先来看看如何来向表中插入记录。我们将使用customer_insert.xml来描述插入操作。代码如下:
下面是customer_insertupdate..xls的代码。在这里,我们首先核对一下客户记录在数据库中是否存在,如果不存在,则插入记录。import net.sf.saxon.Transform;
![]()
public class CustomerOrder...{
public void insert()...{
Transform transformData = new Transform();
String[] args = ...{"customer_insert.xml",
"customer_insertupdate.xsl"};
transformData.doTransform(args, null);
}
}
<xsl:variable name="customerid" select="CUSTOMERID"/>
<xsl:variable name="customer-table">
<sql:query connection="$connection" table="customer"
where="CUSTOMERID='{$customerid}'" column="*"
row-tag="CUSTOMERORDER" column-tag="col"/>
</xsl:variable>
![]()
<xsl:if test="count($customer-table//CUSTOMERORDER) = 0">
<sql:insert table="customer" connection="$connection">
<sql:column name="CUSTOMERID" select="CUSTOMERID"/>
<sql:column name="CUSTOMERLASTNAME" select="CUSTOMERLASTNAME"/>
<sql:column name="CUSTOMERFIRSTNAME" select="CUSTOMERFIRSTNAME"/>
<sql:column name="CUSTOMEREMAIL" select="CUSTOMEREMAIL"/>
</sql:insert>
</xsl:if>
(2) 读取记录
在插入记录后,在这一部分我们将使用sql:query来读取记录。在这里我们使用customer_query.xml向customer_query.xsl传递参数。
上面的xml表示将得到所有ID是123的记录。显然如果想采用这些技术,就必须在程序中动态产生XML文档。customer_query.xsl的内容如下:<?xml version="1.0"?>
<CUSTOMERORDERS>
<CUSTOMERORDER>
<CUSTORDER>
<ORDERID>123</ORDERID>
</CUSTORDER>
</CUSTOMERORDER>
</CUSTOMERORDERS>
<xsl:template match="CUSTOMERORDERS">
<xsl:message>customer_query.xsl :
Connecting to <xsl:value-of select="$database"/>...</xsl:message>
<xsl:message>customer_query.xsl : query records....</xsl:message>
<xsl:apply-templates select="CUSTOMERORDER" mode="Query"/>
<sql:close connection="$connection"/>
</xsl:template>
![]()
<xsl:template match="CUSTOMERORDER" mode="Query">
<xsl:variable name="orderid" select="CUSTORDER/ORDERID"/>
<xsl:variable name="orderitem-table">
<sql:query connection="$connection" table="ORDERITEM" where="ORDERID=
'{$orderid}'" column="*" row-tag="ORDERITEM" column-tag="col"/>
</xsl:variable>
<xsl:message>There are now <xsl:value-of
select="count($orderitem-table//ORDERITEM)"/> orderitems.</xsl:message>
<ORDER>
<xsl:copy-of select="$orderitem-table"/>
</ORDER>
<sql:close connection="$connection"/>
</xsl:template>