zoukankan      html  css  js  c++  java
  • 【JDBC】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);
        }

    }

  • 相关阅读:
    数据库对象命名参考
    写有效率的SQL查询(I)
    一個常用的phpclass類
    写有效率的SQL查询(IV)
    深入浅出理解索引结构
    Java初学者:Jsp开发环境配置全过程
    总结性知识:做网站的一些定律
    如何在JBuilder2007中配置MyEclipse
    幾個有用的ASP Function
    [SQL] 系统存储过程
  • 原文地址:https://www.cnblogs.com/guoxh/p/6552470.html
Copyright © 2011-2022 走看看