eclipse
为了增加代码的复用性,这里使用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 }
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方法和有参,无参构造器
然后写一个接口封装要使用到的方法package dao;import java.util.List;import bean.Emp;public interface EmpDao { //添加员工 public void add(Emp emp); //查询员工 public List
在建立一个接口的实现类,注意看我放的位置,尽量都这么建包,方便使用public void add(Emp emp) {//连接数据库 Connection con=null; PreparedStatement pstm=null; String sql=null;
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(?,?,?)';
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文件将在下一篇写