1.导入jar包
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class Jutil {
static ComboPooledDataSource dataSource = new ComboPooledDataSource();
public static Connection getConnection() {
Connection conn = null;
try {
conn = dataSource.getConnection();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public static void close(ResultSet rs,PreparedStatement ps){
if(rs !=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(ps !=null){
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
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;
public class BaseDao {
public List query(String sql,ResultSetToObject rso,Object...objects) {
List list=new ArrayList();
ResultSet rs=null;
Connection conn=null;
PreparedStatement ps=null;
try {
conn=Jutil.getConnection();
ps=conn.prepareStatement(sql);
setParams(ps,objects);
rs=ps.executeQuery();
while(rs.next()) {
Object o=rso.resultSetToObject(rs);
list.add(o);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Jutil.close(rs, ps);
return list;
}
public int update(String sql,Object...objects) {
int num=0;
Connection conn=null;
PreparedStatement ps=null;
try {
conn=Jutil.getConnection();
ps=conn.prepareStatement(sql);
setParams(ps,objects);
num=ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Jutil.close(null, ps);
return num;
}
private void setParams(PreparedStatement ps, Object...objects) {
if(objects!=null) {
for(int i=0;i<objects.length;i++) {
try {
ps.setObject(i+1, objects[i]);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
package com.hhit.login.util;
import java.sql.ResultSet;
public interface ResultSetToObject {
public abstract Object resultSetToObject(ResultSet res);
}
package com.hhit.login.util;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.hhit.login.entity.Regist;
public class ResultSetToRegist implements ResultSetToObject{
public Object resultSetToObject(ResultSet rs) {
Regist regist = new Regist();
try {
regist.setUsername(rs.getString("username"));
regist.setPwd(rs.getString("pwd"));
} catch (SQLException e) {
e.printStackTrace();
}
return regist;
}
}