典型的dao模式应该包括:
vo:值对象,是表的一个映射
dao接口:封装的是所有数据的操作
dao实现类:实现dao接口
dao工厂:用来创建dao对象
开发步骤
1.定义一个Account类(vo)
只有属性,没有方法,与Account表的结构对应;
2.定义一个AccountDao接口;
public interface AccountDao {
void insert(Account account);
void delete(Integer accountId);
void update(Account account);
}
3.定义实现类:用来实现接口中的方法
未优化的代码:
Account类
public class Account {
Integer accountid;
String name;
Integer remain;
public Account() {
super();
}
public Account(Integer accountid, String name, Integer remain) {
super();
this.accountid = accountid;
this.name = name;
this.remain = remain;
}
public Account(String name, Integer remain) {
super();
this.name = name;
this.remain = remain;
}
public Integer getAccountid() {
return accountid;
}
public void setAccountid(Integer accountid) {
this.accountid = accountid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getremain() {
return remain;
}
public void setremain(Integer remain) {
this.remain = remain;
}
@Override
public String toString() {
return "Account [accountid=" + accountid + ", name=" + name + ", remain=" + remain + "]";
}
}
AccountDao
public interface AccountDao {
void insert(Account account);
void delete(Integer accountId);
boolean update(Account account);
}
AccountDaoImpl
import java.sql.Connection;
import com.mysql.jdbc.PreparedStatement;
public class AccountDaoImpl implements AccountDao {
String sql_insert="insert into account values(null,?,?)";
String sql_delete="delete from account where accountid=?";
String sql_update="update account set name=?,remain=? where accountid=?";
@Override
public void insert(Account account) {
// TODO Auto-generated method stub
try(Connection conn=JdbcUtil.getConnection();
PreparedStatement ps=(PreparedStatement) conn.prepareStatement(sql_insert)){
ps.setString(1, account.getName());
ps.setInt(2, account.getremain());
ps.execute();}
catch(Exception e) {
e.printStackTrace();
}
System.out.println("插入一个帐号"+account);
}
@Override
public void delete(Integer accountId) {
try(Connection conn=JdbcUtil.getConnection();
PreparedStatement ps=(PreparedStatement) conn.prepareStatement(sql_delete)){
ps.setInt(1, accountId);
ps.execute();}
catch(Exception e) {
e.printStackTrace();
}
System.out.println("删除了,accountId= "+accountId);
}
@Override
public boolean update(Account account) {
// TODO Auto-generated method stub
int b=0;
try(Connection conn=JdbcUtil.getConnection();
PreparedStatement ps=(PreparedStatement) conn.prepareStatement(sql_update)){
ps.setString(1, account.getName());
ps.setInt(2,account.getremain());
ps.setInt(3, account.getAccountid());
b=ps.executeUpdate();}
catch(Exception e) {
e.printStackTrace();
}
System.out.println("修改了一个帐号: "+account);
return b>0?true:false;
}
}