dao层:数据接口层,方法层,介于业务逻辑层和数据库之间,进行数据的访问和操作
在实际业务处理过程中,往往需要进行多次数据库的访问。这些访问性质往往是相同的,采用Dao层可以将对数据库访问进行封装,避免经行重复性数据库访问开发操作,同时降低维护的成本。
dao层代码:
package com.nz.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.nz.entity.BankAccount;
import com.nz.util.MySQLDriverUtil;
public class JDBCDao {
//方法区,基础方法区
//查
public List<BankAccount> JDBCSelect() throws Exception {
Connection connection = MySQLDriverUtil.getConnect();
//准备sql
String sql = "select * from bank_account";
//预装载sql
PreparedStatement ps = connection.prepareStatement(sql);
//执行sql
ResultSet result = ps.executeQuery();
//初始化list
List<BankAccount> list = new ArrayList<BankAccount>();
//收集参数
while(result.next()) {
int id = result.getInt(1);
String num = result.getString("num");
double balance = result.getDouble("balance");
//对象收参
BankAccount bankAccount = new BankAccount();
bankAccount.setId(id);bankAccount.setNum(num);bankAccount.setBalance(balance);
list.add(bankAccount);
}
return list;
}
//新增
public boolean JDBCInsert(BankAccount bankAccount) throws Exception {
Connection connection = MySQLDriverUtil.getConnect();
//准备sql
String sql = "INSERT INTO bank_account (num, balance) VALUES ('"+bankAccount.getNum()+"', '"+bankAccount.getBalance()+"')";
//预装载sql
PreparedStatement ps = connection.prepareStatement(sql);
//执行sql 新增 删除 修改 debug
int i = ps.executeUpdate();
//判断是否成功
if(i>0) {
return true;
}
return false;
}
//修改
public boolean JDBCUpdate(BankAccount bankAccount) throws Exception {
Connection connection = MySQLDriverUtil.getConnect();
//准备sql
String sql = "update bank_account set num='"+bankAccount.getNum()+"' where id="+bankAccount.getId()+"";
//预装载sql
PreparedStatement ps = connection.prepareStatement(sql);
//执行sql 新增 删除 修改 debug
int i = ps.executeUpdate();
//判断是否成功
if(i>0) {
return true;
}
return false;
}
//删除
public boolean JDBCDelete(int id) throws Exception {
Connection connection = MySQLDriverUtil.getConnect();
//准备sql
String sql = "delete from bank_account where id="+id+"";
//预装载sql
PreparedStatement ps = connection.prepareStatement(sql);
//执行sql 新增 删除 修改 debug
int i = ps.executeUpdate();
//判断是否成功
if(i>0) {
return true;
}
return false;
}
}