使用JDBC4.0操作XML类型数据 - 编程入门网
作者 佚名技术
来源 NET编程
浏览
发布时间 2012-06-18
"<title>Second Article</title>"+
"<author>Mary Jones</author>"+
"<body>Another short article.</body>"+
"</article>";
static final String XML3 =
"<article>"+
"<title>Third Article</title>"+
"<author>John Smith</author>"+
"<body>Last short article.</body>"+
"</article>";
static final String[] ARTICLES = {XML1, XML2, XML3};
public static void main(String s[])
{
XmlDbTester xdt = new XmlDbTester();
Connection c = xdt.getConnection();
xdt.loadDemoData(c);
xdt.demoXmlResult(c);
xdt.demoXPath(c);
xdt.closeConnection(c);
System.out.println("Done");
System.exit(0);
}
void demoXmlResult(Connection c)
{
try
{
Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT XMLSERIALIZE (DATA AS CLOB) "+
"FROM ARTICLE WHERE ID = 2");
while(rs.next())
System.out.println("The article XML for article with ID = 2: \n"+
rs.getString(1));
s.close();
rs.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
void demoXPath(Connection c)
{
try
{
Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT ID FROM ARTICLE WHERE "+
"XMLEXISTS(''//author[text()=\"John Smith\"]'' PASSING BY REF "+
"DATA)");
while(rs.next())
System.out.println("John Smith wrote article with ID: "+
rs.getInt(1));
s.close();
rs.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
void loadDemoData(Connection c)
{
try
{
Statement s = c.createStatement();
s.execute("CREATE TABLE ARTICLE(ID INTEGER, DATA XML)");
System.out.println("Created demo table: ARTICLE");
s.close();
PreparedStatement ps = null;
int id = 1;
for(String insert : ARTICLES)
{
ps = c.prepareStatement("INSERT INTO ARTICLE (ID, DATA) VALUES "+
"(?, XMLPARSE (DOCUMENT CAST (? AS CLOB) PRESERVE "+
"WHITESPACE))");
ps.setInt(1, id++);
ps.setClob(2, new StringReader(insert));
ps.executeUpdate();
}
System.out.println("Inserted test data into ARTICLE");
if(ps != null )
ps.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
Connection getConnection()
{
Connection c = null;
try
{
c = DriverManager.getConnection("jdbc:derby:XmlDemo;create=true");
c.setAutoCommit(false);
}
catch (Exception e)
{
e.printStackTrace();
}
return c;
}
void closeConnection(Connection c)
{
try
{
c.close();
}
catch(Exception e) {}
}
}
使用JDBC4.0操作XML类型数据(3)时间:2011-03-14 IT168 极地圣火Derby数据库中存在很多专门针对XML的操作符,如XMLPARSE和XMLSERIALIZE,它们将帮助我们将数据转换为字符数据流或字符串,以便我们在程序中使用。在调用这些语句之后,将是我们例子中的具体要完成的任务。在这里,我还会介绍如 |
凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢! |
你可能对下面的文章感兴趣
关于使用JDBC4.0操作XML类型数据 - 编程入门网的所有评论