连数据代码

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;
}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值