对一个简单的JDBC包装器的扩展及应用(1) 本文将对《一个简单的 JDBC 包装器》中的JDBC包装器进行一些扩展,然后介绍一下其在jsp+javabean开发模式中的应用。 最近看了《一个简单的 JDBC 包装器》,觉得这篇文章很有应用价值,我便在自己的开发中使用了它,不过这个包装器也存在一些不足,于是我对它进行了一些扩展。首先原文中的Table类缺少删除功能,我便增加了删除功能。代码如下: public void delRow(Row row) throws SQLException { String ss="";
ss = "delete from "+name+" where ";
for (int i=0; i<row.length(); ++i) { String k = row.getKey( i ); String v = row.get( i ); ss += k+"=´"+v+"´"; if (i != row.length()-1) ss += " and "; } Connection con = database.getConnection(); Statement st = con.createStatement(); st.executeUpdate( ss ); } public void delRow(String conditions)throws SQLException { String ss=""; ss = "delete from "+name+" where "; ss +=conditions; Connection con = database.getConnection(); Statement st = con.createStatement(); st.executeUpdate( ss ); }
这两个函数分别用于删除一个Row和满足一定条件的记录。对于具有主关键字的表,我们可以用下面代码中的方法二来进行删除,如果没有主关键字,我们可以用方法一删除。
示例如下: //方法一 Row e = table.getRow( "id=2001" ); table.delRow(e); //方法二 table.delRow("id=2001");
另外这个包装器没有对查询结果为NULL的情况作处理,我通过修改Table类的execute函数和RowSet类的get函数对这种情况作了处理。具体代码见附件。
下面谈谈利用这个JDBC包装器实现对数据库的封装,假定我们有一个表:student,创建表的Sql语句如下: create table student( id varchar(10) not null primary key, name varchar(16) not null, sex char(2) not null, password varchar(16) not null, department varchar(32) not null )
我们对这个表进行封装,下面是Student类的主要代码: public class Student{
private Row r;
public Student() { r=new Row(); } public Student(Row row) { this.r=row; } private Table getTable() { Database db = new Database( "jdbc:mysql://localhost:3306/manger", "zf", "zf" ); return db.getTable("student"); }
public void setName(String name){ r.put("name",name); } public void setPassword(String pass){ r.put("password",pass); } public void setId(String number){ r.put("id",number); } public void setDepart(String depart){ r.put("department",depart); } public void setSex(String sex){ r.put("sex",sex); } public String getName(){ return r.get("name"); } public String getPassword(){ return r.get("password"); } public String getId(){ return r.get("id"); } public String getDepart(){ return r.get("department"); } public String getSex(){ return r.get("sex"); } /** *condition表示限制条件,如果为空,则插入新记录,否则更新记录 */ public void save(String conditions) throws SQLException{ if(conditions==null) {getTable().putRow(r);} else getTable().putRow(r,conditions);
} /** *由于id作为主关键字,所以我们使用字符串为参数的delRow()函数 */ public void delete()throws SQLException{ //getTable().delRow(this.r); String conditions=""; conditions = "id=" + "´"+getId()+"´"; getTable().delRow(conditions); } }
下面这个类是相应的一个查询类的主要代码: public class StudentFactory{ public static Student findStudentById(String id) throws SQLException{ Row r=getTable().getRow("id="+id); if(r==null) return null; else return new Student(r); } public static Student[] findAllStudents() throws SQLException{ RowSet rs=getTable().getRows("1>0"); if (rs==null) return null; else Student[] stu=null; stu=new Student[rs.length()]; for(int i=0;i<rs.length(); i++){ stu[i]=new Student(rs.get(i)); } return stu; } }
(未完,待续)
|