多语言展示
当前在线:1886今日阅读:86今日分享:14

jsp页面对数据库的增删改

jsp和数据库交互,由于代码过长,我会分三篇分别介绍,
工具/原料

eclipse

方法/步骤
1

为了增加代码的复用性,这里使用dao来写,首先建立一个实体类,和数据库一一映射public class Emp { private int id; private String name; private int age; private double sal;  public Emp(String name, int age, double sal) {  super();  this.name = name;  this.age = age;  this.sal = sal; } public Emp() {  super();  // TODO Auto-generated constructor stub }

2

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 int getAge() {  return age; } public void setAge(int age) {  this.age = age; } public double getSal() {  return sal; } public void setSal(double sal) {  this.sal = sal; } }主要是set,get方法和有参,无参构造器

3

然后写一个接口封装要使用到的方法package dao;import java.util.List;import bean.Emp;public interface EmpDao { //添加员工 public void add(Emp emp); //查询员工 public List listEmp(); //根据id查找员工 public Emp findById(int id); //修改员工 public void udateEmp(Emp emp); //删除员工 public void delete(int id); }

4

在建立一个接口的实现类,注意看我放的位置,尽量都这么建包,方便使用public void add(Emp emp) {//连接数据库  Connection con=null;  PreparedStatement pstm=null;  String sql=null;

5

String name=emp.getName();  int age=emp.getAge();  double sal=emp.getSal();  try { con=DBUtil.getConnection();   sql='insert into t_emp(name,age,sal)values(?,?,?)';

6

pstm=con.prepareStatement(sql);   pstm.setString(1, name);   pstm.setInt(2, age);   pstm.setDouble(3, sal);   pstm.executeUpdate();  } catch (SQLException e) {   System.out.println('连接异常');  }finally{   DBUtil.closeConnection(con);  } }之前写过DBUtil文件了,不知道的可以翻开我之前的文章查看

注意事项

这里只是实现类,jsp文件将在下一篇写

推荐信息