第一步:创建dao工具类
public class DBConnect {
private static final String className= "oracle.jdbc.driver.OracleDriver";
private static final String url = "jdbc:oracle:thin:@localhost:1521:orcl";
private static final String user = "humm";
private static final String password = "tiger";
private Connection conn=null;
//数据库连接(构造方法)
public DBConnect(){
try {
Class.forName(className);
this.conn = DriverManager.getConnection(url,user,password);
} catch (Exception e) {
e.printStackTrace();
}
}
public Connection getConnection(){
return conn;
}
//关闭
public void close(){
if(conn!=null){
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
第二步:增删改查--实现层
public String addEmp() throws Exception{
HttpServletRequest request = ServletActionContext.getRequest();//这样已经被摈弃了,一般是在action层直接@setter属性值,对象则@setter@getter
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
String birthday = request.getParameter("birthday");
resMap = searchEmpInfoService.addEmp(name,age,birthday);
return SUCCESS;
}
@Override //增加员工
public Map<String, Object> addEmp(String name, int age, String birthday) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
DBConnect db = new DBConnect();
Connection conn = db.getConnection();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date d = sdf.parse(birthday);
String addEmpSq ="insert into EMP(id,NAME,age,Birthday)values(EMPID_SEQ.Nextval,?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(addEmpSq);
pstmt.setString(1, name);
pstmt.setInt(2, age);
pstmt.setDate(3, new java.sql.Date(d.getTime()));
int len =pstmt.executeUpdate();
map.put("updateLen", len);
pstmt.close();
db.close();
return map;
}
//查的实现层方法
PreparedStatement pstmt2 = conn.prepareStatement(sqlcountParam.toString());
if(id!=""&&id!=null){
int empId = Integer.parseInt(id);
++number2;
pstmt2.setInt(number2, empId);
}
if(name!=""&&name!=null){
++number2;
pstmt2.setString(number2, name);
}
if(birthday!=""&&birthday!=null){
++number2;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date date = sdf.parse(birthday);
Date d = new Date(date.getTime());
pstmt2.setDate(number2, d);
}
number2=0;
ResultSet rs2 = pstmt2.executeQuery();//2222222
int count = 0;
while(rs2.next()){
count = rs2.getInt(1);
}
map.put("total", count);