public class DBTable {
PRotected Connection conn;
protected tableName;
public DBTable(String tableName) {
this.tableName = tableName;
this.conn = ...;
}
public void clear() {
PreparedStatement st = conn.prepareStatement("DELETE FROM "+tableName);
try {
st.executeUpdate();
}finally{
st.close();
}
}
public int getCount() {
PreparedStatement st = conn.prepareStatement("SELECT COUNT(*) FROM"+tableName);
try {
ResultSet rs = st.executeQuery();
rs.next();
return rs.getInt(1);
}finally{
st.close();
}
}
}
public class ParticipantsInDB extends DBTable {
public ParticipantsInDB() {
super("participants");
}
public void addParticipant(Participant part) {
...
}
public void deleteParticipant(String participantId) {
setDeleteFlag(participantId, true);
}
public void restoreParticipant(String participantId) {
setDeleteFlag(participantId, false);
}
private void setDeleteFlag(String participantId, boolean b) {
...
}
public void reallyDelete() {
PreparedStatement st = conn.prepareStatement(
"DELETE FROM "+
tableName+
" WHERE deleteFlag=true");
try {
st.executeUpdate();
}finally{
st.close();
}
}
public int countParticipants() {
PreparedStatement st = conn.prepareStatement(
"SELECT COUNT(*) FROM "+
tableName+
" WHERE deleteFlag=false");
try {
ResultSet rs = st.executeQuery();
rs.next();
return rs.getInt(1);
}finally{
st.close();
}
}
}
ParticipantsInDB partsInDB = ...;
Participant kent = new Participant(...);
Participant paul = new Participant(...);
partsInDB.clear();
partsInDB.addParticipant(kent);
partsInDB.addParticipant(paul);
partsInDB.deleteParticipant(kent.getId());
System.out.println("There are "+partsInDB.getCount()+ "participants");
新闻热点
疑难解答