java通过Servlet连接mysql数据库

第一步:创建Servlet

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

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

/**
 * Servlet implementation class ConnectionServlet
 */
public class ConnectionServlet extends HttpServlet {
	Connection con;
	public void init() {
		String driver = getInitParameter("driver");
		String url = getInitParameter("url");
		String name = getInitParameter("user");
		String pass = getInitParameter("password");
		try {
			Class.forName(driver);
			con=DriverManager.getConnection(url,name,pass);
		}catch(ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public ConnectionServlet() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */

		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException,ServletException{
			request.setCharacterEncoding("UTF-8");
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter out=response.getWriter();
			String bookName=request.getParameter("bookName");
			ResultSet rst=getBook(bookName);
			out.println("");
			try {
				while(rst.next()) {
					out.println("");
					out.println("");
					out.println("");
					out.println("");
					out.println("");
				}
				out.println("
图书名出版社价格
"+rst.getString("bookname")+""+rst.getString("publisher")+""+rst.getString("price")+"
"); rst.close(); }catch(Exception e) { } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException,ServletException{ // TODO Auto-generated method stub //init(); doGet(request, response); } public ResultSet getBook(String bookName) { try { Statement stm=con.createStatement(); ResultSet result=stm.executeQuery("select * from books where bookname='"+bookName+"'"); return result; }catch(Exception e) { return null; } } }

第二步:配置xml文件

在eclipse中找到该项目的xml文件
java通过Servlet连接mysql数据库_第1张图片

修改xml

java通过Servlet连接mysql数据库_第2张图片

第三步:编写一个html来测试servlet





Insert title here



输入图书名,点击按钮操作.
图书名:

实验结果

运行html
java通过Servlet连接mysql数据库_第3张图片

查询反馈
java通过Servlet连接mysql数据库_第4张图片

你可能感兴趣的:(java,mysql,jsp,java,Servlet,mysql)