jdbc servlet 基础连接数据库实现 WEB项目

创建web project

导入 oracle jar包 一般在 D:\oracle\product\10.2.0\db_2\jdbc\lib 目录下 ojdbc14.jar

连接字符串:

mysql driver: org.gjt.mm.mysql.Driver

URL: jdbc:mysql://localhost:3306/test

oracle dirver: oracle.jdbc.driver.OracleDriver

URL: jdbc:oracle:thin:@localhost:1521:dbwang

创建 BaseDao

public class BaseDao {
	public static final String DRIVER="org.gjt.mm.mysql.Driver";
	public static final String URL="jdbc:mysql://localhost:3306/test";
	public static final String USERNAME="root";
	public static final String PWD="root";

//	获得连接
	public Connection getConn() throws ClassNotFoundException,SQLException{
		Class.forName(DRIVER);
		Connection conn=DriverManager.getConnection(URL, USERNAME, PWD);
		return conn;
	}
	
//	释放资源
	public void closeAll(Connection conn,Statement state,ResultSet rs){
		try {
			if(rs!=null){ rs.close();}
			if(state!=null){ state.close();}
			if(conn!=null){ conn.close();}
		} catch (Exception e) {
			e.printStackTrace();
			
		}
		
		
	}
	
//	执行CUD指令
	public int executeSQL(String sql,String [] args){
		int rs=0;
		Connection conn=null;
		PreparedStatement state=null;
		try {
			conn=getConn();
			state=conn.prepareStatement(sql);
			if(args!=null&&args.length>0){
				for (int i = 0; i < args.length; i++) {
					state.setString(i+1, args[i]);
				}
				
			}
			rs=state.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{closeAll(conn, state, null);
			}
		return rs;
		
	}

}

再创建 StuinfoDao 继承 BaseDao

public class StuinfoDao extends BaseDao {
	
	/**
	 * 增加
	 */
	public int addStu(Stuinfo stu){
		int rs=0;
		String sql="insert into stuinfo (name,age,sex,address) value (?,?,?,?)";
		String []  args={stu.getName(),stu.getAge()+"",stu.getSex(),stu.getAddress()};
		rs=executeSQL(sql, args);
		return rs;
	}

	/**
	 * 删除
	 */
	public int delStu(int id){
		int rs=0;
		String sql="delete from stuinfo where id="+id;
		String []  args={id+""};
		rs=executeSQL(sql, args);
		return rs;
	}
	
	

	/**
	 * 修改
	 */
	public int updateStu(Stuinfo stu){
		int rs=0;
		String sql="update stuinfo name=?,age=?,sex=?,address=? where id=?";
		String []  args={stu.getName(),stu.getAge()+"",stu.getSex(),stu.getAddress(),stu.getId()+""};
		rs=executeSQL(sql, args);
		return rs;
	}

//  9:26
	/**
	 * 查找页数
	 */
	public int findStuPageCount(Stuinfo stu,int number){
		int result=0;
		int count=0;
		Connection conn=null;
		PreparedStatement state=null;
		ResultSet rs=null;
		String sql="select count(*) as c from stuinfo where 1=1 ";
		List list=new ArrayList();
		if (stu!=null&&!stu.equals("")) {
			if(stu.getId()!=0){
				sql+=" id=?";
				list.add(stu.getId()+"");
			}
			if(stu.getName()!=null&&!stu.getName().equals("")){
				sql+=" name like ?";
				list.add("%"+stu.getName()+"%");
			}
			if(stu.getAge()!=0){
				sql+=" age=?";
				list.add(stu.getAge()+"");
			}
			if(stu.getSex()!=null&&!stu.getSex().equals("")){
				sql+=" sex=?";
				list.add(stu.getSex());
			}
			if(stu.getAddress()!=null&&!stu.getAddress().equals("")){
				sql+=" address like ?";
				list.add("%"+stu.getAddress()+"%");
			}
		}
		Object [] args=(Object[])list.toArray();
		try {
			conn=getConn();
			state=conn.prepareStatement(sql);
			if(args!=null&&args.length>0){
				for (int i = 0; i < args.length; i++) {
					state.setObject(i+1, args[i]);
				}
			}
			rs=state.executeQuery();
			if(rs.next()){
				count=rs.getInt("c");
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{ closeAll(conn, state, rs);}
		result=(count+number-1)/number;
		return result;
	}
	
	
	/**
	 * 查询
	 * 
	 */
	public List<Stuinfo> findStuinfo(Stuinfo stu,int currretPage,int number){
		List<Stuinfo> stus=new ArrayList<Stuinfo>();
		Connection conn=null;
		PreparedStatement state=null;
		ResultSet rs=null;
		String sql="select * from stuinfo where 1=1 ";
		List list=new ArrayList();
		if (stu!=null&&!stu.equals("")) {
			if(stu.getId()!=0){
				sql+=" id=?";
				list.add(stu.getId()+"");
			}
			if(stu.getName()!=null&&!stu.getName().equals("")){
				sql+=" name like ?";
				list.add("%"+stu.getName()+"%");
			}
			if(stu.getAge()!=0){
				sql+=" age=?";
				list.add(stu.getAge()+"");
			}
			if(stu.getSex()!=null&&!stu.getSex().equals("")){
				sql+=" sex=?";
				list.add(stu.getSex());
			}
			if(stu.getAddress()!=null&&!stu.getAddress().equals("")){
				sql+=" address like ?";
				list.add("%"+stu.getAddress()+"%");
			}
		}
		sql+=" limit ?,?";
		int num=(currretPage-1)*number;
		list.add(num);
		list.add(number);
		Object [] args=(Object[])list.toArray();
		try {
			conn=getConn();
			state=conn.prepareStatement(sql);
			if(args!=null&&args.length>0){
				for (int i = 0; i < args.length; i++) {
					state.setObject(i+1, args[i]);
				}
			}
			rs=state.executeQuery();
			while(rs.next()){
				int id=rs.getInt("id");
				String name=rs.getString("name");
				int age=rs.getInt("age");
				String sex=rs.getString("sex");
				String address=rs.getString("address");
				
				Stuinfo newstu=new Stuinfo(id, name, age, sex, address);
				stus.add(newstu);
				
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{ closeAll(conn, state, rs);}
		return stus;
		
	}
	

	/**
	 * 根据ID查询
	 */
	public Stuinfo findStuById(int id){
		Stuinfo stu =null;
		String sql="select * from stuinfo id="+id;
		Connection conn=null;
		Statement state=null;
		ResultSet rs=null;
		try {
			conn=getConn();
			state=conn.createStatement();
			rs=state.executeQuery(sql);
			if (rs.next()) {
				stu=new Stuinfo(id, rs.getString("name"), rs.getInt("age"), rs.getString("sex"), rs.getString("address"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{ closeAll(conn, state, rs);}
		return stu;
		
		
	}
	
}

创建 servlet  DoAdd extends HttpServlet

public class DoAdd extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public DoAdd() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		doPost(request, response);
		
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		String name=request.getParameter("name");
		String strage=request.getParameter("age");
		String sex=request.getParameter("sex");
		String address=request.getParameter("address");
		int age=0;
		if (strage!=null&&!strage.equals("")) {
			age=Integer.parseInt(strage);
		}
		new StuinfoDao().addStu(new Stuinfo(name, age, sex, address));
		response.sendRedirect("doSearchStu");
		
		
		
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
一定要记得配置 web.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <description>显示description</description>
    <display-name>显示display</display-name>
    <servlet-name>DoAdd</servlet-name>
    <servlet-class>com.tc.stuinfoservlet.DoAdd</servlet-class>
  </servlet>
  <servlet>
    <description>显示description</description>
    <display-name>显示display</display-name>
    <servlet-name>DoDel</servlet-name>
    <servlet-class>com.tc.stuinfoservlet.DoDel</servlet-class>
  </servlet>
  <servlet>
    <description>显示description</description>
    <display-name>显示display</display-name>
    <servlet-name>DoUpdate</servlet-name>
    <servlet-class>com.tc.stuinfoservlet.DoUpdate</servlet-class>
  </servlet>
  <servlet>
    <description>显示description</description>
    <display-name>显示display</display-name>
    <servlet-name>Dos</servlet-name>
    <servlet-class>com.tc.stuinfoservlet.Dos</servlet-class>
  </servlet>
  <servlet>
    <description>显示description</description>
    <display-name>显示display</display-name>
    <servlet-name>DoSearchStu</servlet-name>
    <servlet-class>com.tc.stuinfoservlet.DoSearchStu</servlet-class>
  </servlet>
  <servlet>
    <description>显示description</description>
    <display-name>显示display</display-name>
    <servlet-name>DoFindStu</servlet-name>
    <servlet-class>com.tc.stuinfoservlet.DoFindStu</servlet-class>
  </servlet>






  <servlet-mapping>
    <servlet-name>DoAdd</servlet-name>
    <url-pattern>/doAdd</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>DoDel</servlet-name>
    <url-pattern>/doDel</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>DoUpdate</servlet-name>
    <url-pattern>/doUpdate</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>Dos</servlet-name>
    <url-pattern>/servlet/Dos</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>DoSearchStu</servlet-name>
    <url-pattern>/doSearchStu</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>DoFindStu</servlet-name>
    <url-pattern>/doFindStu</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>



你可能感兴趣的:(oracle,Web,mysql,jdbc,servlet)