时间:2021-07-01 10:21:17 帮助过:1人阅读
4. 曾删改查方法
public class SaveOrUpdate { @Test public void save(){ Connection conn = null; Statement stmt = null; try { conn = JDBCUtils.getConnection(); stmt = conn.createStatement(); String sql = "insert into student(name,gender)values(‘波多野结衣妹子‘,‘女‘)"; int count = stmt.executeUpdate(sql); System.out.println(count); } catch (Exception e) { throw new RuntimeException(e); }finally{ JDBCUtils.close(stmt, conn); } } //注意:1. update table student报错,只能写update student!!!! //如:"UPDATE student SET NAME=‘瑶瑶‘, gender=‘女‘ WHERE id = ‘2‘ AND NAME=‘zhangsan‘" //2. set多个值时候只能用逗号隔开不能用and隔开!!!! @Test public void update(){ Connection conn = null; Statement stmt = null; try { conn = JDBCUtils.getConnection(); stmt = conn.createStatement(); String sql = "UPDATE student SET NAME=‘我爱瑶瑶‘, gender=‘女‘ WHERE id =2"; stmt.executeUpdate(sql); } catch (Exception e) { throw new RuntimeException(e); }finally{ JDBCUtils.close(stmt, conn); } } @Test public void delete(){ Connection conn = null; Statement stmt = null; try { conn = JDBCUtils.getConnection(); stmt = conn.createStatement(); String sql = "delete from student WHERE id =2"; stmt.executeUpdate(sql); } catch (Exception e) { throw new RuntimeException(e); }finally{ JDBCUtils.close(stmt, conn); } } public List<Student> findAll(){ Connection conn = null; Statement stmt = null; try { conn = JDBCUtils.getConnection(); stmt = conn.createStatement(); String sql = "SELECT * FROM STUDENT"; ResultSet resultSet = stmt.executeQuery(sql); List<Student> studentList = new ArrayList<>(); while(resultSet.next()){ Student student = new Student(); student.setId(resultSet.getInt("id"));//列名必须与数据库的字段一样但不区分大小写 student.setName(resultSet.getString("NAME")); student.setGender(resultSet.getString("GeNdEr")); studentList.add(student); } return studentList; } catch (SQLException e) { throw new RuntimeException(e); } } @Test public void iterate(){ List<Student> studentList = findAll(); for(Student stu : studentList){ System.out.println(stu.getId()+"***"+stu.getName()+"****"+stu.getGender()); } } } class Student{ private int id; private String name; private String gender; public Student() {} public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", gender=" + gender + "]"; } }
JDBC 数据库连接
标签: