book.xml
xsi:schemaLocation="http://sauria.com/schemas/apache-xml-book/book
http://www.sauria.com/schemas/apache-xml-book/book.xsd"
version="1.0">
Indianapolis, Indiana
Book.java
package com.sauria.apachexml.ch1;
public class Book {
String title;
String author;
String isbn;
String month;
int year;
String publisher;
String address;
public String getAddress() {
return address;
}
public String getAuthor() {
return author;
}
public String getIsbn() {
return isbn;
}
public String getMonth() {
return month;
}
public String getPublisher() {
return publisher;
}
public String getTitle() {
return title;
}
public int getYear() {
return year;
}
public void setAddress(String string) {
address = string;
}
public void setAuthor(String string) {
author = string;
}
public void setIsbn(String string) {
isbn = string;
}
public void setMonth(String string) {
month = string;
}
public void setPublisher(String string) {
publisher = string;
}
public void setTitle(String string) {
title = string;
}
public void setYear(int i) {
year = i;
}
public String toString() {
return title + " by " + author;
}
}
BookHandler.java
package com.sauria.apachexml.ch1;
import java.util.Stack;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
public class BookHandler extends DefaultHandler {
private Stack elementStack = new Stack();
private Stack textStack = new Stack();
private StringBuffer currentText = null;
private Book book = null;
public Book getBook() {
return book;
}
public void startElement(
String uri,
String localPart,
String qName,
Attributes attributes)
throws SAXException {
currentText = new StringBuffer();
textStack.push(currentText);
elementStack.push(localPart);
if (localPart.equals("book")) {
String version = attributes.getvalue("", "version");
if (version != null && !version.equals("1.0"))
throw new SAXException("Incorrect book version");
book = new Book();
}
}
public void endElement(String uri, String localPart,
String qName)
throws SAXException {
String text = textStack.pop().toString();
if (localPart.equals("book")) {
} else if (localPart.equals("title")) {
book.setTitle(text);
} else if (localPart.equals("author")) {
book.setAuthor(text);
} else if (localPart.equals("isbn")) {
book.setIsbn(text);
} else if (localPart.equals("month")) {
book.setMonth(text);
} else if (localPart.equals("year")) {
int year;
try {
year = Integer.parseInt(text);
} catch (NumberFormatException e) {
throw new SAXException("year must be a number");
}
book.setYear(year);
} else if (localPart.equals("publisher")) {
book.setPublisher(text);
} else if (localPart.equals("address")) {
book.setAddress(text);
} else {
throw new SAXException("Unknown element for book");
}
elementStack.pop();
}
public void characters(char[] ch, int start, int length)
throws SAXException {
currentText.append(ch, start, length);
}
public void warning(SAXParseException ex) throws SAXException {
System.err.println(
"[Warning] " + getLocationString(ex) + ": " +
ex.getMessage());
}
public void error(SAXParseException ex) throws SAXException {
System.err.println(
"[Error] " + getLocationString(ex) + ": " +
ex.getMessage());
}
public void fatalError(SAXParseException ex)
throws SAXException {
System.err.println(
"[Fatal Error] " + getLocationString(ex) + ": " +
ex.getMessage());
throw ex;
}
/** Returns a string of the location. */
private String getLocationString(SAXParseException ex) {
StringBuffer str = new StringBuffer();
String systemId = ex.getSystemId();
if (systemId != null) {
int index = systemId.lastIndexOf('/');
if (index != -1)
systemId = systemId.substring(index + 1);
str.append(systemId);
}
str.append(':');
str.append(ex.getLineNumber());
str.append(':');
str.append(ex.getColumnNumber());
return str.toString();
}
}
SAXMain.java
package com.sauria.apachexml.ch1;
import java.io.IOException;
import org.apache.xerces.parsers.SAXParser;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
public class SAXMain {
public static void main(String[] args) {
XMLReader r = new SAXParser();
BookHandler bookHandler = new BookHandler();
r.setContentHandler(bookHandler);
r.setErrorHandler(bookHandler);
try {
r.parse("book.xml");
System.out.println(bookHandler.getBook().toString());
System.out.println(bookHandler.getBook().getAddress().toString());
} catch (SAXException se) {
System.out.println("SAX Error during parsing " +
se.getMessage());
se.printStackTrace();
} catch (IOException ioe) {
System.out.println("I/O Error during parsing " +
ioe.getMessage());
ioe.printStackTrace();
} catch (Exception e) {
System.out.println("Error during parsing " +
e.getMessage());
e.printStackTrace();
}
}
}
封装数据库操作,目的就是为了隐藏java.sql包内的类,在编码中去掉核心的数据库操作代码。以杜绝直接数据库操作容易带来的资源未释放问题。同时也减少了数据库操作的编码量。
但是很多网友在封装时,却喜欢返回结果集(ResultSet对象),那么这个封装就没有意义了。
1. 又是直接操作核心数据库类,跟封装前几乎没什么变化。
2. 结果集总是依赖于它使用的连接(Connection)对象。因此当连接对象在方法内被关闭后,你返回的ResultSet就没有用了。
如果真的要获得查询数据库的结果集,就把结果集对象内的所有数据,转储到以Map为元素的List对象内。
当然,这种方式,不能适应大数据量的查询,不过如果真的碰到大数据量的查询,那用什么封装都不好,还是得直接数据库操作. :)))
下面是简单的数据库操作Javabean的代码
DbWrapper.java
import java.sql.*;
import java.util.*;
public class DbWrapper
{
// 定义连接池对象为静态变量,将一直存在,直到工作目录关闭。
private static DataSource ds = null;
// 1.用连接池的方式获得连接
// 如果不是做多数据库程序,推荐使用此方法
// 相关内容:在tomcat管理界面配置连接池
public static Connection openConnection() throws Exception
{
// 只需要初始化1次
if ( ds == null )
{
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
DataSource ds = (DataSource) envContext.lookup("jdbc/MyDataSource");
}
return ds.getConnection();
}
// 2.用jdbc驱动获得连接
// 相关内容:JSP数据库连接大全
public static Connection openConnection(
String driver,
String url,
String username,
String password)
throws Exception
{
Class.forName(driver).newInstance();
return DriverManager.getConnection(url, username, password);
}
public static void closeConnection(Connection conn) throws Exception
{
if ( conn != null )
{
conn.close();
}
}
public static int executeUpdate(String sql) throws Exception
{
int count = 0;
Connection conn = null;
Statement stmt = null;
try
{
conn = openConnection();
stmt = conn.createStatement();
count = stmt.executeUpdate(sql);
}
catch ( Exception e )
{
throw e;
}
finally
{
closeConnection(conn);
}
return count;
}
public static List executeQuery(String sql) throws Exception
{
List list = new ArrayList();
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try
{
conn = openConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
while ( rs.next() )
{
Map map = new HashMap();
for ( int i = 1; i <= rsmd.getColumnCount(); i++ )
{
map.put(rsmd.getColumnName(i), rs.getObject(i));
}
list.add(map);
}
}
catch ( Exception e )
{
e.printStackTrace();
}
finally
{
if ( rs != null ) rs.close();
closeConnection(conn);
}
return list;
}
}
使用示例:
// 1.对于insert, update, delete语句
int count = DbWrapper.executeUpdate(sql);
// 2.对于selete语句
java.util.List list = DbWrapper.executeQuery(sql);
// 方法一:按名字取值,注意大小写是严格区分的
for ( int i = 0; i < list.size(); i++ )
{
java.util.Map map = (java.util.Map)list.get(i);
out.println(mag.get("column_name").toString());
}
// 方法二:遍历取值
for ( int i = 0; i < list.size(); i++ )
{
java.util.Map map = (java.util.Map)list.get(i);
for (java.util.Iterator it = map.keySet().iterator(); it.hasNext();)
{
String column_name = it.next().toString());
// 取值时注意null判断
out.println(column_name + " = " + map.get(column_name) == null ? "" : map.get(column_name).toString());
}
}