JDBC-Eclipse & 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.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Jdbc_Servlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public Jdbc_Servlet() {
        super();
    }

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/student?user=root&password=&characterEncoding=utf-8";
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        out.print("<html>");
        out.print("<head><title>使用JDBC访问数据库实例</title></head>");
        out.print("<body>");
        try{
            Class.forName(driver);
            Connection conn = DriverManager.getConnection(url);
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("select * from studentInfo");
            while(rs.next()){
                out.print("学号:"+rs.getInt("stu_number")+"<br>");
                out.print("姓名:"+rs.getString("stu_name")+"<br>");
                out.print("性别:"+rs.getString("stu_gender")+"<br>");
                out.print("年龄:"+rs.getInt("stu_age")+"<br>");
                out.print("地址:"+rs.getString("stu_address")+"<br><br>");
            }
            if(rs != null){
                rs.close();
            }
            if(stmt != null){
                stmt.close();
            }
            if(conn != null){
                conn.close();
            }
        }
        catch(ClassNotFoundException ex){
            ex.printStackTrace();
        }
        catch(SQLException ex){
            ex.printStackTrace();
        }
        out.print("</body>");
        out.print("</html>");
    
    }

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

上一篇:在数学建模中学MATLAB


下一篇:《30天自制操作系统》09_day_学习笔记