荔园在线
荔园之美,在春之萌芽,在夏之绽放,在秋之收获,在冬之沉淀
[回到开始]
[上一篇][下一篇]
发信人: Lg (创造人生的传奇), 信区: Java
标 题: DBHandler -- 0.1
发信站: 荔园晨风BBS站 (Thu Jul 5 17:12:24 2001) , 转信
DBHandler的0.1版本,主要是配置文档的剖析,程序的整体结构。
package jdbc_study;
/**
* Title: JDBC Study
* Description:
* Copyright: Copyright (c) 2001
* Company: Vista
* @author Gang Liu
* @version 1.0
*/
import java.util.*;
import java.io.*;
import java.sql.*;
import org.apache.log4j.*;
import vista.sql.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
public final class DBHandler {
private static Category cat = Category.getInstance(DBHandler.class.getName());
private static boolean firstInstance = true;
private static Hashtable configuration = null;
private String poolName = null;
private String handlerID = null;
private String querySQL = null;
private DBConnectionManager dbConnM = null;
private Connection conn = null;
private PreparedStatement preStmt = null;
public static synchronized DBHandler getHandler(
String poolName, String handlerID) {
DBHandler handler = new DBHandler(poolName, handlerID);
if (firstInstance) { //第一次创建实例
//需要初始化
cat.debug("go to init()");
handler.init();
//Test
DBConnectionManager.getInstance();
firstInstance = false;
}
if (configuration == null) {
cat.debug("config error");
return null;
}
cat.debug("check poolName and handlerID");
Object object = configuration.get(poolName);
if (object != null) {
Querys querys = (Querys)object;
String sql = querys.getQuery(handlerID);
if (sql == null) {
cat.debug("handlerID error");
handler = null;
}
else
handler.querySQL = sql;
}
else {
cat.debug("can not get pool: " + poolName);
handler = null;
}
if (handler != null) {
handler.dbConnM = DBConnectionManager.getInstance();
if (handler.dbConnM != null) {
handler.conn = handler.dbConnM.getConnection(poolName);
if (handler.conn != null) {
cat.debug("got database connection");
}
else {
cat.warn("can not get database connection");
handler.dbConnM.release();
handler = null;
}
}
else {
cat.warn("can not get database manager");
handler = null;
}
}
return handler;
}
public void setInt(int parameterIndex, int x)
throws SQLException {
if (this.preStmt == null) {
this.initPreparedStatement();
}
this.preStmt.setInt(parameterIndex, x);
}
public void setString(int parameterIndex, String x)
throws SQLException {
if (this.preStmt == null) {
this.initPreparedStatement();
}
this.preStmt.setString(parameterIndex, x);
}
public int executeUpdate()
throws SQLException {
/**
* @todo executeUpdate(String sql)?
*/
return this.preStmt.executeUpdate();
}
public void close() throws SQLException {
/**
* @todo close()?
*/
if (this.preStmt != null)
this.preStmt.close();
if ((this.conn != null) && (this.dbConnM != null)) {
this.dbConnM.rtnConnection(this.poolName, this.conn);
this.dbConnM.release();
this.conn = null;
this.dbConnM = null;
}
}
private void initPreparedStatement()
throws SQLException {
this.preStmt = this.conn.prepareStatement(this.querySQL);
}
/**
* 类内部的自测代码。
*/
public static void main(String[] args) throws SQLException {
PropertyConfigurator.configure("log.config");
for (int i = 0; i < 1024; i++)
try {
System.out.println(Runtime.getRuntime().totalMemory());
DBHandler handler = DBHandler.getHandler("test", "ADD");
if (handler == null) {
cat.warn("dbhandler is null");
return;
}
handler.setString(1, "liugang" + i);
handler.setString(2, "pass");
handler.executeUpdate();
handler.close();
}
catch (SQLException e) {}
}
//私有构造函数
private DBHandler(String poolName, String handlerID)
{
this.poolName = poolName;
this.handlerID = handlerID;
}
private void init() {
/**
* @todo 获取配置信息
*/
//读取配置文件信息
InputStream is = getClass().getResourceAsStream("/dbhandler.xml");
//不进行有效性文档检验
boolean validation = false;
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setValidating(validation);
XMLReader xmlReader = null;
try {
// Create a JAXP SAXParser
SAXParser saxParser = spf.newSAXParser();
// Get the encapsulated SAX XMLReader
xmlReader = saxParser.getXMLReader();
} catch (Exception ex) {
cat.error("",ex);
return;
}
// Set the ContentHandler of the XMLReader
XMLConfigParse configHandler = new XMLConfigParse();
xmlReader.setContentHandler(configHandler);
// Set an ErrorHandler before parsing
xmlReader.setErrorHandler(new XMLConfigParse.MyErrorHandler(System.err));
try {
// Tell the XMLReader to parse the XML document
xmlReader.parse(new InputSource(is));
} catch (SAXException se) {
cat.error("",se);
} catch (IOException ioe) {
cat.error("",ioe);
}
this.configuration = configHandler.getConfiguration();
}
}
class XMLConfigParse extends DefaultHandler {
// A Hashtable with tag names as keys and Integers as values
//private Hashtable tags;
private Hashtable pools;
private String nameOfOperation;
private StringBuffer buffer;
private Querys querys;
public Hashtable getConfiguration() {
return this.pools;
}
// Parser calls this once at the beginning of a document
public void startDocument() throws SAXException {
//tags = new Hashtable();
this.pools = new Hashtable();
}
// Parser calls this for each element in a document
public void startElement(String namespaceURI, String localName,
String rawName, Attributes atts)
throws SAXException
{
if (localName.equals("DBHandler"))
return;
else if (localName.equals("DBPool")) {
String name = atts.getValue("name");
String type = atts.getValue("type");
//System.err.println(name);
//System.err.println(type);
if ((name != null) && (type != null)) {
querys = new Querys();
querys.setTypeOfDataBase(type);
pools.put(name, querys);
}
else {
this.querys = null;
}
}
else if (localName.equals("Operation")) {
if (this.querys != null) {
this.nameOfOperation = atts.getValue("name");
this.buffer = new StringBuffer();
}
}
}
public void characters(char[] ch, int start, int end)
throws SAXException {
if (this.buffer != null)
this.buffer.append(ch, start, end);
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (localName.equals("Operation")) {
if (this.querys != null) {
this.querys.addQuery(this.nameOfOperation, buffer.toString().trim());
//System.err.println(this.nameOfOperation);
//System.err.println(buffer.toString().trim());
}
}
}
// Parser calls this once after parsing a document
public void endDocument() throws SAXException {
}
// Error handler to report errors and warnings
static class MyErrorHandler implements ErrorHandler {
/** Error handler output goes here */
private PrintStream out;
MyErrorHandler(PrintStream out) {
this.out = out;
}
/**
* Returns a string describing parse exception details
*/
private String getParseExceptionInfo(SAXParseException spe) {
String systemId = spe.getSystemId();
if (systemId == null) {
systemId = "null";
}
String info = "URI=" + systemId +
" Line=" + spe.getLineNumber() +
": " + spe.getMessage();
return info;
}
// The following methods are standard SAX ErrorHandler methods.
// See SAX documentation for more info.
public void warning(SAXParseException spe) throws SAXException {
out.println("Warning: " + getParseExceptionInfo(spe));
}
public void error(SAXParseException spe) throws SAXException {
String message = "Error: " + getParseExceptionInfo(spe);
throw new SAXException(message);
}
public void fatalError(SAXParseException spe) throws SAXException {
String message = "Fatal Error: " + getParseExceptionInfo(spe);
throw new SAXException(message);
}
}
}
class Querys {
private String typeOfDataBase = null;
private Hashtable querys = null;
public Querys() {
this.querys = new Hashtable();
}
public void setTypeOfDataBase(String type) {
this.typeOfDataBase = type;
}
public void addQuery(String opID, String sql) {
/**
* @todo 将该query加入
*/
this.querys.put(opID, sql);
}
public void delQuery(String opID) {
/**
* @todo 将该query删除
*/
}
public String getQuery(String opID) {
/**
* @todo 获取该query
*/
return (String)this.querys.get(opID);
}
}
--
不退缩,即使有日我会跌倒,不退避,痛得更深攀得到更高。
icq: 70670666
Email: gang_l@21cn.com & gang_l@hotmail.com
Homepage: 重新制作...
※ 来源:.荔园晨风BBS站WWW bbs.szu.edu.cn. [FROM: 202.104.150.159]
[回到开始]
[上一篇][下一篇]
荔园在线首页 友情链接:深圳大学 深大招生 荔园晨风BBS S-Term软件 网络书店