package y2jsp.students.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.jsp.jstl.sql.Result;
import javax.servlet.jsp.jstl.sql.ResultSupport;
import javax.sql.DataSource;
public class BaseDao {
protected Connection conn;
protected PreparedStatement ps;
protected ResultSet rs;
/**
* 加载驱动建立数据库的连接
* @return 这个连接Connection
*/
/* public static synchronized Connection getConnection(){
String driverClassName=ReadProperties.getIntance().getProperty("driver");
String url=ReadProperties.getIntance().getProperty("url");
String user=ReadProperties.getIntance().getProperty("user");
String pass=ReadProperties.getIntance().getProperty("pass");
Connection conn=null;
try{
Class.forName(driverClassName);
conn=DriverManager.getConnection(url,user,pass);
return conn;
}catch(Exception ex){
ex.printStackTrace();
}
return null;
}*/
public Connection getConn(String jndiName){
try{
Context context=new InitialContext();
DataSource ds=(DataSource)context.lookup("java:comp/env/"+jndiName);
return ds.getConnection();
}catch(Exception ex){
ex.printStackTrace();
return null;
}
}
/**
* 关闭连接释放资源
* @param conn
* @param ps
* @param rs
*/
public void closeAll(Connection conn,PreparedStatement ps,ResultSet rs){
try{
if(rs!=null){
rs.close();
rs=null;
}
if(ps!=null){
ps.close();
ps=null;
}
if(conn!=null){
conn.close();
conn=null;
}
}catch(Exception ex){
ex.printStackTrace();
}
}
/**
* 数据的增删改操作
* @param sql
* @param values
* @return
*/
public int doExecuteSQL(String sql,List values){
try{
conn=this.getConn("jdbc/common");
ps=conn.prepareStatement(sql);
this.setValues(ps, values);
int s=ps.executeUpdate();
return s;
}catch (Exception ex){
ex.printStackTrace();
return 0;
}finally{
this.closeAll(conn, ps, null);
}
}
public Result getAllDataInfo(String sql,List values){
try{
conn=this.getConn("jdbc/common");
ps=conn.prepareStatement(sql);
this.setValues(ps, values);
rs=ps.executeQuery();
return ResultSupport.toResult(rs);
}catch(Exception ex){
ex.printStackTrace();
return null;
}finally{
this.closeAll(conn, ps, rs);
}
}
/**
* 遍历传递过来的参数值
* @param ps
* @param values
*/
public void setValues(PreparedStatement ps,List values){
if(values!=null){
for(int i=0;i<values.size();i++){
try{
ps.setObject(i+1,i);
}catch (Exception ex){
ex.printStackTrace();
}
}
}
}
}