这里的简化代码即封装。
用之前写过的新闻项目来举例,之前的整个项目都是在WebConnect中完成的,但现在封装代码我们需要再java Resources中的src下建包谢东西。也是我们以前在eclipse中常用的三个包:
实体类:entity;帮助类:DBhelper;方法类:dao
用之前写过的新闻模糊查询为例:
DBhelper
package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class DBHelper {
private static String user="scott";
private static String upwd="tiger";
private static String cname="oracle.jdbc.driver.OracleDriver";
private static String url="jdbc:oracle:thin:@localhost:1521:orcl";
static {
try {
Class.forName(cname);
} catch (ClassNotFoundException e) {
// TODO: handle exception
e.printStackTrace();
}
}
public static Connection getCon() {
Connection con=null;
try {
con=DriverManager.getConnection(url, user, upwd);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return con;
}
public static void closeDB(Connection con,PreparedStatement ps,ResultSet rs) {
try {
if(con!=null) {
con.close();
}
if(ps!=null) {
ps.close();
}
if(rs!=null) {
rs.close();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public static int getNextId(String tableName,String col) {
int id=1;
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
con=DBHelper.getCon();
ps=con.prepareStatement("select max("+col+") from "+tableName);
rs=ps.executeQuery();
if(rs.next()) {
id=rs.getInt(1)+1;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
DBHelper.closeDB(con, ps, rs);
}
return id;
}
}
entity(news)
package entity;
import java.sql.Date;
public class News {
private int nid;
private int tid;
private String ntitle;
private String nzz;
private String nnr;
private String nzy;
private Date ndate;
private int nlook;
private String nimage;
public News() {
super();
}
public News(int tid, String ntitle, String nzz, String nnr, String nzy, Date ndate, int nlook, String nimage) {
super();
this.tid = tid;
this.ntitle = ntitle;
this.nzz = nzz;
this.nnr = nnr;
this.nzy = nzy;
this.ndate = ndate;
this.nlook = nlook;
this.nimage = nimage;
}
public News(int nid, int tid, String ntitle, String nzz, String nnr, String nzy, Date ndate, int nlook,
String nimage) {
super();
this.nid = nid;
this.tid = tid;