日期:2014-05-16 浏览次数:20562 次
J2ee项目开发过程中用到的数据库操作类
此数据库操作封装类在一个省级项目中使用到,在一个集团公司的科技管理项目中也使用过.
package jing.dbnew;
import java.sql.*;
import java.util.*;
import javax.sql.rowset.CachedRowSet;
import oracle.jdbc.rowset.OracleCachedRowSet;
import com.sun.rowset.CachedRowSetImpl;
/**
* Title:数据库操作类,有数据事物控制功能,请注意main函数中的调用事例
* @author 欧朝敬
* QQ:35712069
* 手机:13873195792
* @version 1.0
*/
public class DBManager {
public DBManager(){
}
/**
* 开始事务
*
*/
public void beginTransaction() {
try {
Connection con = ConnectionFactory.getInstance().getConnection();
con.setAutoCommit(false);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 回滚事务
*
*/
public void rollbackTransactoin() {
try {
Connection con = ConnectionFactory.getInstance().getConnection();
con.rollback();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 提交事务
*
*/
public void commitTransaction() {
try {
Connection con = ConnectionFactory.getInstance().getConnection();
con.commit();
con.setAutoCommit(true);
ConnectionFactory.getInstance().closeConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 结束事务
*
*/
// public void endTransaction() {
// try {
// Connection con = ConnectionFactory.getInstance().getConnection();
// con.commit();
// con.setAutoCommit(true);
// ConnectionFactory.getInstance().closeConnection();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
public boolean execute(String sql) throws Exception {
System.out.println("execute:" + sql);
boolean re = false;
Connection con = null;
PreparedStatement pstmt = null;
try {
con = ConnectionFactory.getInstance().getConnection();
pstmt =con.prepareStatement(sql);
re = pstmt.execute();
}catch(Exception ex){
ex.printStackTrace();
con.rollback();
} finally {
if (pstmt != null) {
pstmt.close();
}
}
return re;
}
/**
* 批量执行SQL语句,在一个事物里
* @param sql
* @return
* @throws Exception
*/
public int[] executeBatch(String[] sql) throws Exception {
int[] re=null;;
Connection con = null;
Statement stmt = null;
try {
con = ConnectionFactory.getInstance().getConnection();
con.setAutoCommit(false);
stmt =con.createStatement();
stmt.clearBatch();
for(int i=0;i<sql.length;i++){
stmt.addBatch(sql[i]);
System.out.println("executeBatch:" + sql[i]);
}
re = stmt.executeBatch();
&nb