java+servlet+jsp连接数据库的增删改查

1.首先建一个公共的包,里面包括连接数据库的方法,不用每次都连接数据库。
public String url="jdbc:mysql://localhost:3306/rwgl?useSSL=false";
	@SuppressWarnings("unused")
	public String userName="root";//数据库的账号
	@SuppressWarnings("unused")
	public String pwd="password";//数据库的密码
protected void initDriver() {//数据加载驱动
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

获取数据库的链接

 
  
protected Connection getConn() {
		// 在连接的时候,应该先加载数据库驱动
		initDriver();
		try {
			conn = DriverManager.getConnection(url, userName, pwd);
		} catch (SQLException e) {

			e.printStackTrace();
		}

		return conn;
	}

2.创建实体类

package com.systop.rwgl.employee.model;

import java.io.Serializable;
import java.util.Date;

public class Employee implements Serializable{

	
	private static final long serialVersionUID = -5469025483066661789L;
	//唯一的主键
	private int id;
	private int userid;
	private int deptid;
	private int no;
	private String name;
	private String sex;
	//生日是date的数据类型
        private Date birthday;
	private String duty;
	private String address;
	private String number;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public int getUserid() {
		return userid;
	}
	public void setUserid(int userid) {
		this.userid = userid;
	}
	public int getDeptid() {
		return deptid;
	}
	public void setDeptid(int deptid) {
		this.deptid = deptid;
	}
	
	
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	
	public int getNo() {
		return no;
	}
	public void setNo(int no) {
		this.no = no;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	
	
	public String getDuty() {
		return duty;
	}
	public void setDuty(String duty) {
		this.duty = duty;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public String getNumber() {
		return number;
	}
	public void setNumber(String number) {
		this.number = number;
	}
	public void setBirthday(String parameter) {
		// TODO Auto-generated method stub	
	}
}

3.在前台的界面上的form表单上,action连接的时候,增加一个action的参数,给他一个特定的值

action="${pageContext.request.contextPath}/employee?action=add"

然后在servlet的文件中写有关增删改查的,初学者适用

 
  
package com.systop.rwgl.employee.controller;
import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.systop.rwgl.employee.dao.EmployeeDao;
import com.systop.rwgl.employee.model.Employee;
import com.systop.rwgl.user.model.User;

public class EmployeeServlet extends HttpServlet{
	
	private static final long serialVersionUID = 1L;
	/**
	 * doget的提交方式在使用a标签的时候使用,
	 * 是将get的提交方式转化为post的提交方式。
	 * dopost的是将按钮的提交方式
	 * 
	 * 转化提交方式
	 */
	public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		doPost(request,response);
	}
	public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		
		       String action = request.getParameter("action");
                       //当你前台界面设置的action的值等于add的时候执行下面的语句
		       if(action != null && action.equals("add")) {
		           EmployeeDao employeedao = new EmployeeDao();
                          //测试有没有执行	
                          System.out.println("?????????????????"+action);
			
			try {
	                  //封装一个employee的实体类,将前台文本框中的值获取到,存入employee中
                          Employee employee = new Employee();		
                          //强制转化no的值,int类型的转为String类型的
	                  employee.setNo(Integer.valueOf(request.getParameter("no")));
                          //双引号中的值跟前台文本框中的name的值相同
	 	          employee.setName(request.getParameter("name"));
		          employee.setSex(request.getParameter("sex"));
		          //必须跟数据库中的类型相同					
                          employee.setBirthday(Date.valueOf(request.getParameter("birth")));
		          employee.setDuty(request.getParameter("zhiwu"));
		          employee.setAddress(request.getParameter("zhuzhi"));
		          employee.setNumber(request.getParameter("number"));
                          //Dao文件中有addEmployee的方法,在这里调用	        	        
                          employeedao.addEmployee(employee);
	        	  //添加完成提交之后首页显示所有的信息
	        	try {
			    List list = employeedao.getEmployee("");
			    for(int i = 0;i

4.在Dao中的文件写增删改查的方法

 
  
package com.systop.rwgl.employee.dao;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.mysql.jdbc.Connection;
import com.systop.core.dao.BaseDao;
import com.systop.rwgl.employee.model.Employee;
import com.systop.rwgl.user.model.User;

public class EmployeeDao extends BaseDao{
    /**
     * 在数据库中添加信息
     * @param employee
     * @throws Exception
     */
	public void addEmployee(Employee employee) throws Exception{
		String sql = "insert into task_employee (EM_NO,EM_XM,EM_XB,EM_SR,EM_ZW,EM_ZZ,EM_SFZH) values (?,?,?,?,?,?,?)";//添加的insert语句
		Connection conn = null;
		PreparedStatement stmt = null;
		try {
			conn = (Connection) getConn();
			stmt = conn.prepareStatement(sql);
			/*System.out.println(sql);*/
			stmt.setInt(1, employee.getNo());//从servlet文件中封装到employee中,从employee中获取各个字段的值
			stmt.setString(2, employee.getName());//从employee中得到值的顺序必须跟sql语句中的顺序一致
			stmt.setString(3, employee.getSex());
			stmt.setDate(4, (Date) employee.getBirthday());
			stmt.setString(5, employee.getDuty());
			stmt.setString(6, employee.getAddress());
			stmt.setString(7, employee.getNumber());
			stmt.execute();
			/*System.out.println(stmt);*/
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				conn.close();
			}
			if (stmt != null) {
				stmt.close();
			}
		}
	}
	/**
	 * 在数据库中查询所有的记录,并显示在页面上
	 * @param deptNo
	 * @return
	 * @throws SQLException
	 */
	public List getEmployee(String deptNo) throws SQLException{	
     //查询select的语句
		String sql = "SELECT ID,EM_NO,EM_XM,EM_XB,EM_SR,EM_ZW,EM_ZZ,EM_SFZH  FROM task_employee";
		Connection conn = null;
		PreparedStatement stmt = null;
		List employeeList = new ArrayList();
		try {
			conn = (Connection) getConn();
			stmt = conn.prepareStatement(sql);
			
			ResultSet rs = stmt.executeQuery();
			while (rs.next()) {
				Employee u = new Employee();
				u.setId(rs.getInt(1));
				u.setNo(rs.getInt(2));
				u.setName(rs.getString(3));
				u.setSex(rs.getString(4));
				u.setBirthday(rs.getDate(5));
				u.setDuty(rs.getString(6));
				u.setAddress(rs.getString(7));
				u.setNumber(rs.getString(8));
				
				employeeList.add(u);	
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				conn.close();
			}
			if (stmt != null) {
				stmt.close();
			}
		}
		return employeeList;
	}
	/**
	 * 按照id来删除数据库中的信息
	 * @param employee
	 * @throws SQLException
	 */
	public void deleteEmployee(Employee employee) throws SQLException {
		String sql="delete from task_employee where id=?";//delete的sql语句
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			conn = (Connection) getConn();
			stmt = conn.prepareStatement(sql);
			stmt.setInt(1, employee.getId());//只得到主键id的值,并且删除id的那一条信息
			
			stmt.execute();		
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				conn.close();
			}
			if (stmt != null) {
				stmt.close();
			}
		}
	}
	/**
	 * 查询一条记录
	 * @param id
	 * @return
	 * @throws SQLException
	 */
	public List getOne(int id) throws SQLException
	  {
	    String sql = " select ID,TASK_USER_ID,TASK_DEPT_ID,EM_NO,EM_XM,EM_XB,EM_SR,EM_ZW,EM_ZZ,EM_SFZH from task_employee where ID=?";
	    Connection conn = null;
      PreparedStatement stmt = null;
      conn = (Connection) getConn();
		stmt = conn.prepareStatement(sql);
		stmt.setInt(1, id);
		ResultSet rs = stmt.executeQuery();
		List employeeOne = new ArrayList();
		while (rs.next())
	    {
	      Employee em = new Employee();
	       em.setId(rs.getInt(1));
	       em.setUserid(rs.getInt(2));
			em.setDeptid(rs.getInt(3));
			em.setNo(rs.getInt(4));
			em.setName(rs.getString(5));
			em.setSex(rs.getString(6));
			em.setBirthday(rs.getDate(7));
			em.setDuty(rs.getString(8));
			em.setAddress(rs.getString(9));
			em.setNumber(rs.getString(10));
			employeeOne.add(em);
	    }
		return employeeOne;
	  }
	/**
	 * 修改信息
	 * @param employee
	 * @throws SQLException
	 */
	public void updateEmployee(Employee employee) throws SQLException{
		String sql = "update task_employee set EM_NO=?,EM_XM=?,EM_XB=?,EM_SR=?,EM_ZW=?,EM_ZZ=?,EM_SFZH=? where ID=?";//update的sql语句获取到修改之后的信息之后,插入到update语句中
		Connection conn = null;
	    PreparedStatement stmt = null;
	    try {
			conn = (Connection) getConn();
			stmt = conn.prepareStatement(sql);
			/*System.out.println(sql);*/
			stmt.setInt(1, employee.getNo());
			stmt.setString(2, employee.getName());
			stmt.setString(3, employee.getSex());
			stmt.setDate(4, (Date) employee.getBirthday());
			stmt.setString(5, employee.getDuty());
			stmt.setString(6, employee.getAddress());
			stmt.setString(7, employee.getNumber());
			stmt.setInt(8, employee.getId());
			stmt.execute();
			/*System.out.println(stmt);*/
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				conn.close();
			}
			if (stmt != null) {
				stmt.close();
			}
		}
	}
}



你可能感兴趣的:(java+servlet+jsp连接数据库的增删改查)