package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.naming.*;
import javax.sql.*;
public abstract class BaseDao {
Connection conn=null;
PreparedStatement pstmt =null;
ResultSet rs=null;
protected Connection getConn() throws Exception{
Context ctx=new InitialContext();
DataSource ds=(DataSource)ctx.lookup("java:comp/env/jdbca");
conn=ds.getConnection();
return conn;
}
protected List executeQuery(String strSql ,String[] params){
List lst=null;
try{
conn=getConn();
pstmt=conn.prepareStatement(strSql);
int i=0;
for(String param : params){
pstmt.setString(++i, param);
}
rs=pstmt.executeQuery();
lst=createObject(rs);
}catch(Exception ex){
ex.printStackTrace();
}finally{
closeAll();
}
return lst;
}
protected abstract List createObject(ResultSet rs)throws SQLException;
protected void closeAll(){
try{
if(rs!=null) rs.close();
if(pstmt!=null) pstmt.close();
if(conn!=null) conn.close();
}catch(Exception ex){
System.out.println(ex.getMessage());
}
}
public int executeUpdate(String strSql,String[] params){
int i=-1;
try {
conn=getConn();
pstmt=conn.prepareStatement(strSql);
int j=0;
for(String param :params){
pstmt.setString(++j, param);
}
i=pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally{
closeAll();
}
return i;
}
public int getCount(String strSql,String[] params){
int i=-1;
try {
conn=getConn();
pstmt=conn.prepareStatement(strSql);
int j=0;
for(String param :params){
pstmt.setString(++j, param);
}
rs=pstmt.executeQuery();
if(rs.next()){
i=rs.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
closeAll();
}
return i;
}
}
连数据代码
最新推荐文章于 2022-03-03 00:21:06 发布