Druid的增删改
1.构造一个Student类
封装姓名、年龄、id和电话等属性
public class Student { private String name; private String age; private String id; private String phone; public Student() { } public Student(String name, String age, String id, String phone) { this.name = name; this.age = age; this.id = id; this.phone = phone; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age='" + age + '\'' + ", id='" + id + '\'' + ", phone='" + phone + '\'' + '}'; } }
注意:一定要使用无参的构造函数,否则使用增删改查的时候可能会报错
2.增
public int addInformation(Student student) { Connection conn = null; try { conn = JDBCUtils.getConnection(); String sql = "insert into student values(?,?,?,?)"; QueryRunner runner = new QueryRunner(); int update = runner.update(conn, sql, student.getName(), student.getAge(), student.getId(), student.getPhone()); return update; } catch (Exception e) { e.printStackTrace(); } finally { JDBCUtils.closeResource(conn); } return 0; }
返回操作的个数
3.删
public int deleteInformation(String name) { Connection conn = null; try { conn = JDBCUtils.getConnection(); String sql = "delete from student where `name`=?"; QueryRunner runner = new QueryRunner(); int update = runner.update(conn, sql, name); return update; } catch (Exception e) { e.printStackTrace(); } finally { JDBCUtils.closeResource(conn); } return 0; }
4.改
public int changeInformation(Student student, String name) { Connection conn = null; try { conn = JDBCUtils.getConnection(); String sql = "update student set `name`=?, age=?, id=?, phone=? where name=?"; QueryRunner runner = new QueryRunner(); int update = runner.update(conn, sql, student.getName(), student.getAge(), student.getId(), student.getPhone(), name); return update; } catch (Exception e) { e.printStackTrace(); } finally { JDBCUtils.closeResource(conn); } return 0; }