package com.qhit;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.log4j.Logger;
/**
* 数据库操作基本类
* @author Administrator
*
*/
public class BaseDao {
private Logger log = Logger.getLogger(this.getClass());//做日志
private Connection conn;
private Statement st;
private PreparedStatement pst;
private ResultSet rs;
private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
public BaseDao(){
this.conn = this.getConn();
try {
this.st = conn.createStatement();
} catch (SQLException e) {
log.error(e.getMessage(), e);
throw new UserException(e);
}
}
/**
* 执行不带参的sql语句
* @param sql
*/
public void exeSql(String sql){
try{
st.executeUpdate(sql);
}catch(Exception e){
log.error(e.getMessage(), e);
throw new UserException(e);
}
}
/**
* 执行带参的sql语句
*/
public void exeSql(String sql,Object param[]){
try{
pst = conn.prepareStatement(sql);
if(param != null&¶m.length != 0){
for(int i = 0;i<param.length;i++){
pst.setObject(i+1, param[i]);
}
}
pst.executeUpdate();
}catch(Exception e){
log.error(e.getMessage(), e);
throw new UserException();
}
}
/**
* 执行查询sql语句
*/
public ResultSet getRs(String sql){
ResultSet rers = null;
try{
rers = st.executeQuery(sql);
}catch(Exception e){
log.error(e.getMessage(),e);
throw new UserException(e);
}
return rers;
}
/**
* 执行带参的sql语句
* @param sql
* @param param
* @return
*/
public ResultSet getRs(String sql,Object param[]){
try{
pst = conn.prepareStatement(sql);
if(param != null && param.length != 0){
for(int i = 0;i<param.length;i++){
pst.setObject(i+1, param[i]);
}
}
rs = pst.executeQuery();
}catch(Exception e){
log.error(e.getMessage(), e);
throw new UserException(e);
}
return rs;
}
/**
* 开始一个事务
*/
public void beginTran(){
try {
conn.setAutoCommit(false);
} catch (SQLException e) {
log.error(e.getMessage(), e);
throw new UserException(e);
}
}
/**
* 提交一个事务
*/
public void commitTran(){
try {
conn.commit();
} catch (SQLException e) {
log.error(e.getMessage(), e);
throw new UserException(e);
}
}
/**
* 回滚一个事务
*/
public void rollbackTran(){
try {
conn.rollback();
} catch (SQLException e) {
log.error(e.getMessage(), e);
throw new UserException(e);
}
}
/**
* 取得自动增长的主键号
*/
public int getId(){
int i = 0;
String sql = "select @@identity";
try{
rs = st.executeQuery(sql);
if(rs.next()){
i = rs.getInt(1);
}
}catch(Exception e){
log.error(e.getMessage(),e);
throw new UserException(e);
}
return i;
}
/**
* 从threadLocal中得到数据库连接
* @return
*/
public Connection getConn(){
Connection conn = null;
conn = threadLocal.get();
if(conn == null){//没有数据库连接,则通过单例模式得到数据库连接
conn = GetConn.getGetConn().getConn();
threadLocal.set(conn);
}
return conn;
}
/**
* 关闭数据库的资源
*
*/
public void closeAll(){
try{
if(rs != null)rs.close();
if(pst != null)pst.close();
if(st != null)st.close();
if(conn != null){
conn.close();
threadLocal.set(null);
}
}catch(Exception e){
log.error(e.getMessage(), e);
throw new UserException(e);
}
}
}
- 1
- 2
前往页