zoukankan      html  css  js  c++  java
  • 01_10_SERVLET如何连接Mysql数据库

    01_10_SERVLET如何连接Mysql数据库

    1. 实现类

    public void doGet(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {

    Connection conn = null;

    Statement stmt = null;

    ResultSet rs = null;

    response.setContentType("text/html;charset=utf-8");

    PrintWriter out = response.getWriter();

    out.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">");

    out.println("<HTML>");

    out.println("<HEAD><TITLE>Servlet连接MySQL数据库</TITLE></HEAD>");

    out.println("<BODY>");

    out.print("<table align="center" border="1"><tr align="center"><td>查询world库中city表中的Name列信息</td></tr>");

    try {

    Class.forName("com.mysql.jdbc.Driver");

    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/world?user=root&password=123456");

    stmt = (Statement) conn.createStatement();

    rs = stmt.executeQuery("select * from city");

    while (rs.next()) {

    out.println("<tr align="center"><td>" +rs.getString("name") + "</td></tr>");

    }

    out.println("</table>");

    } catch (ClassNotFoundException e) {

    e.printStackTrace();

    } catch (SQLException e) {

    e.printStackTrace();

    } finally {

    if (rs != null) {

    try {

    rs.close();

    rs = null;

    } catch (SQLException e) {

    e.printStackTrace();

    }

    }

    if (stmt != null) {

    try {

    stmt.close();

    stmt = null;

    } catch (SQLException e) {

    e.printStackTrace();

    }

    }

    if (conn != null) {

    try {

    conn.close();

    conn = null;

    } catch (SQLException e) {

    e.printStackTrace();

    }

    }

    }

    out.println("</BODY>");

    out.println("</HTML>");

    out.flush();

    out.close();

    }

  • 相关阅读:
    HTTP/2的优先级
    JavaScript 日期权威指南
    岂曰无衣与子同袍
    Android项目中实现native调用
    关键渲染路径
    @ModelAttribute使用详解
    @SessionAttribute使用详解
    @ControllerAdvice 拦截异常并统一处理
    js获取文件MD5值
    Mybatis分页插件PageHelper的配置和使用方法
  • 原文地址:https://www.cnblogs.com/flyback/p/8824529.html
Copyright © 2011-2022 走看看