Java第八次作业
《Java技术》第八次作业
(一)学习总结
1.用思维导图对本周的学习内容进行总结。
参考资料: XMind。
2.通过实验内容中的具体实例说明在执行executeUpdate()方法和 executeQuery()方法中使用动态参数时,为什么要使用 PreparedStatement接口而不使用Statement,比较使用两种接口的不同 之处。
PreparedStatement接口是Statement接口的子接口,使用它的好处有三个
一:简化代码,便于sql语句的书写
二:有效的禁止sql语句的注入,例如:用户名和密码,使用PreparedStatement接口的方法,可防止不正确的输入登陆成功,提高
数据库系统的安全性
三:最大可能的提高了效率
例子:
// 获取所有数据
public ArrayList<Pet> queryAllData() {
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
ArrayList<Pet> list=new ArrayList<Pet>();
try{
conn=JDBCUtils.getConnection(1);//获得链接对象,用 SQLSEVER数据库连接方法
stmt=conn.createStatement();//建立SQL语句的对象,对象 类型为Statement接口
String sql="select no,variety,age,sums,price from pet";//查询语句
rs=stmt.executeQuery(sql);//执行SQL查询语句
while(rs.next()){
Pet thisPet=new Pet();
thisPet.setNo(rs.getString("no"));
thisPet.setVariety(rs.getString("variety"));
thisPet.setAge(rs.getInt("age"));
thisPet.setSum(rs.getInt("sums"));
thisPet.setPrice(rs.getDouble("price"));
list.add(thisPet);//将查询出的这个宠物信息存放到list宠物集合中
}
return list;
}catch(Exception e){
e.printStackTrace();
}finally{
JDBCUtils.close(conn);
}
return null;
}
// 删除数据
public boolean delPet(String delNo) {
boolean result=false;
Connection conn=null;
PreparedStatement pstmt=null;
try{
conn=JDBCUtils.getConnection(1);//用SQLSEVER数据库 连接方法连接
String sql="delete from pet where no=?";
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, delNo);
if(pstmt.executeUpdate()>0){
result=true;
}
}catch(Exception e){
e.printStackTrace();
}finally{
JDBCUtils.close(conn);
}
return result;
}
3.其他需要总结的内容。
(二)实验总结
类图结构:
问题1:AdminService方法里的删除服务从boolean类型改为了int类型,方便做后续判断,我没有注意到,这里出警告改了半天
原因:AdminDialog方法里若值为1,进行删除操作;若值为2,提示没有这个编号;若为0,提示删除失败
解决方案:将返回值类型改为int,并修改相应代码块
问题2:没有办法连接数据库
原因:不能只在数据库里添加数据
解决方案:将对应数据库分离出来,并将其导入到eclipse中
(三)代码托管
- 码云commit历史截图