- 论坛徽章:
- 0
|
(一)DbPool.java:
package com.db;
import java.sql.*;
import javax.naming.*;
import javax.sql.*;
public class DbPool {
private static String strError = "";
private static Object poolLock = new Object();
private static DataSource connectionPool;
private Connection conn = null;
public Connection getConnection() {
synchronized (poolLock) {
if (connectionPool == null) {
try {
InitialContext ctx = new InitialContext();
connectionPool = (DataSource) ctx.lookup("java:comp/env/jdbc/DbPool");
}
catch (Exception e) {
strError = "DbPool[0]:" + e.getMessage();
//System.out.println( e.getMessage() );
return null;
}
}
}//synchronized
try {
conn = connectionPool.getConnection();
conn.setAutoCommit(false);
}catch (SQLException e) {
strError = "DbPool[1]:" + e.getMessage();
//System.out.println( e.getMessage() );
return null;
}
return conn;
}//end getConnection()
public String getError() {
return strError;
}
}
(二)SQLExecute.java:
package com.db;
import java.sql.*;
public class SQLExecute {
private String strError = "";
DbPool dbPool = new DbPool();
private Connection conn = dbPool.getConnection();
//返回查询(select)结果方法
public ResultSet executeQuery(String sql){
if ( conn == null ){//没有拿到连接
strError = dbPool.getError();
return null;
}
ResultSet rs = null;
Statement stmt = null;
try {
//允许记录集指针跳转 rs.last(); rs.previous();
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery(sql);
}catch (SQLException e) {
strError = "SQLExecute[0]:" + e.getMessage();
//System.out.println( e.getMessage() );
return null;
}
return rs;
}
//返回执行(insert,update,delete)结果方法
public int executeUpdate(String sql) {
int i=0;
try {
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
i = stmt.executeUpdate(sql);
conn.commit();
}catch (SQLException e) {
strError = "SQLExecute[1]:" + e.getMessage();
//System.out.println( e.getMessage() );
i=-1;
}
return i;
}
//事务处理方法
public int executeUpdatePre(String sql) {
int i=0;
try {
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
i = stmt.executeUpdate(sql);
}catch (SQLException e) {
strError = "SQLExecute[2]:" + e.getMessage();
//System.out.println( e.getMessage() );
i=-1;
}
return i;
}
//事务提交
public boolean Commit() {
boolean b = false;
try {
if(conn != null) conn.commit();
b = true;
}catch (SQLException e) {
strError = "SQLExecute[3]:" + e.getMessage();
//System.out.println( e.getMessage() );
return false;
}
return b;
}
//关闭数据连接方法
public boolean closeConn() {
boolean b = false;
try {
if(conn != null) conn.close();
}catch (SQLException e) {
strError = "SQLExecute[4]:" + e.getMessage();
//System.out.println( e.getMessage() );
return false;
}
return b;
}
public String getError() {
return strError;
}
}
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/4404/showart_166066.html |
|