核心代码:
Connection的工具类:详见:JDBC数据库连接
StuDao的接口:
public interface StuDaointer {
public void addStu(Stu stu);
public void delStu(int sid);
public void updStu(Stu stu);
public Stu getOneStu(int sid);
public List getAllStu();
}
公共的DAO///*************************************\\\
public abstract class CommonDao {
private Connection conn;
private PreparedStatement pre;
private SQLDBConnutil myconn=SQLDBConnutil.getSQLDBConnutil();
private ResultSet rs;
//所有的添,删,改的方法
protected int update(String sql,Object[] obj){
int n=0;
conn=myconn.getConnection();
try {
pre=conn.prepareStatement(sql);
if(obj!=null && obj.length>0){
for(int i=0;i<obj.length;i++){
pre.setObject(i+1, obj[i]);
}
}
n=pre.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
} finally{
myconn.free(null, pre, conn);
}
return n;
}
protected abstract Object MappingRow(ResultSet rs);
protected Object getone(String sql,Object[] obj){
Object myobj=null;
conn=myconn.getConnection();
try {
pre=conn.prepareStatement(sql);
if(obj!=null && obj.length>0){
for(int i=0;i<obj.length;i++){
pre.setObject(i+1, obj[i]);
}
}
rs=pre.executeQuery();
if(rs.next()){
myobj=this.MappingRow(rs);
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}finally{
myconn.free(rs, pre, conn);
}
return myobj;
}
protected List getall(String sql,Object[] obj){
List list=new ArrayList();
conn=myconn.getConnection();
try {
pre=conn.prepareStatement(sql);
if(obj!=null && obj.length>0){
for(int i=0;i<obj.length;i++){
pre.setObject(i+1, obj[i]);
}
}
rs=pre.executeQuery();
while(rs.next()){
list.add(this.MappingRow(rs));
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}finally{
myconn.free(rs, pre, conn);
}
return list;
}
}
具体对象的Dao实现如下:
public class StuDaoImple extends CommonDao implements StuDaointer {
public void addStu(Stu stu) {
String sql="insert into stu values(?,?,?)";
Object[] obj=new Object[]{stu.getSname(),stu.getSsex(),new java.sql.Date(stu.getSbrith().getTime())};
super.update(sql, obj);
}
public void delStu(int sid) {
String sql="delete stu where s_id=?";
Object[] obj=new Object[]{sid};
super.update(sql, obj);
}
public List getAllStu() {
String sql="select * from stu";
return super.getall(sql, null);
}
public Stu getOneStu(int sid) {
String sql="select * from stu where s_id=?";
Object[] obj=new Object[]{sid};
return (Stu) super.getone(sql, obj);
}
public void updStu(Stu stu) {
String sql="update stu set s_name=?,s_sex=?,s_brith=? where s_id=?";
Object[] obj=new Object[]{stu.getSname(),stu.getSsex(),new java.sql.Date(stu.getSbrith().getTime()),stu.getSid()};
super.update(sql, obj);
}
@Override
protected Object MappingRow(ResultSet rs) {
Stu stu=new Stu();
try {
stu.setSid(rs.getInt("s_id"));
stu.setSname(rs.getString("s_name"));
stu.setSsex(rs.getString("s_sex"));
stu.setSbrith(rs.getDate("s_brith"));
} catch (SQLException e) {
e.printStackTrace();
}
return stu;
}
}