JDBC_dao模式学习笔记
1.新建一个Dao的包,在里面声明一个接口,接口里声明数据库的访问规则
public interface StuDao {
//1.查询
void findAll();
//2.添加
void insert();
//3.删除
void delete();
//4.修改
void update();
}
2.新建一个Dao接口的实现类,具体实现接口里面的访问规则
public class StuDaoimpl implements StuDao{
Connection conn=null;
Statement sta=null;
ResultSet res=null;
@Override
public void findAll() {
try {
//1.注册驱动
conn = jdbcutil.getconn();
//2.创建链接
sta = conn.createStatement();
//3.执行sql语句
String sql = "select * from exam";
res = sta.executeQuery(sql);
//循环遍历数据
while(res.next()) {
int id= res.getInt("id");
String name = res.getString("name");
int chinese= res.getInt("chinese");
int math= res.getInt("math");
int english= res.getInt("english");
System.out.println(id+" "+name+" "+chinese+" "+math+" "+english);
}
} catch (Exception e) {
// TODO: handle exception
}finally {
jdbcutil.re(res, sta, conn);
}
}
public void insert() {
try {
//1.注册驱动
Connection conn = jdbcutil.getconn();
//2.建立链接
Statement sta = conn.createStatement();
//3.执行数据库
String sql = "insert into exam values(null,'姜小白',66,66,66)";
int i=sta.executeUpdate(sql);
if(i>0) {
System.out.println("添加成功");
}else {
System.out.println("添加失败");
}
} catch (Exception e) {
// TODO: handle exception
}finally {
jdbcutil.re(sta, conn);
}
}
public void delete() {
try {
//1.注册驱动
conn = jdbcutil.getconn();
//2.创建链接对象Statement
sta = conn.createStatement();
//3.执行sql语句
String sql = "delete from exam where id=10";
int i = sta.executeUpdate(sql);
if(i>0) {
System.out.println("删除成功");
}else {
System.out.println("删除失败");
}
} catch (Exception e) {
}finally {
jdbcutil.re(sta, conn);
}
}
public void update() {
try {
//1.注册驱动
conn = jdbcutil.getconn();
//2.创建连接对象Statement
sta = conn.createStatement();
//3.执行sql语句
String sql = "update exam set name='老王',chinese=100,math=60,english=50 where id=8";
int i=sta.executeUpdate(sql);
if(i>0) {
System.out.println("更新成功");
}else {
System.out.println("更新失败");
}
} catch (Exception e) {
// TODO: handle exception
}finally {
jdbcutil.re(sta, conn);
}
}
}
3.新建一个test来实现测试
public class jdbctest {
public void findAllTest() {
StuDao dao=new StuDaoimpl();
dao.findAll();
}
public void insert() {
StuDao dao=new StuDaoimpl();
dao.insert();
}
public void delete() {
StuDao dao=new StuDaoimpl();
dao.delete();
}
@Test
public void update() {
StuDao dao=new StuDaoimpl();
dao.update();
}
}