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 );
}
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;
}
}
String ss = "";
if (conditions==null) {
ss = "INSERT INTO " name "(";
for (int i=0;i<row.length(); i) {
String k = row.getKey( i );
ss = k;
if (i != row.length()-1)
ss = ", ";
}
ss =") VALUES (";
for (int j=0; j<row.length(); j) {
String v = row.get( j );
ss = "'" v "'";
if (j != row.length()-1)
ss = ", ";
}
ss = ")";
}