美文网首页
2019-02-20

2019-02-20

作者: 么啊么 | 来源:发表于2022-09-03 22:05 被阅读0次
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.sql.*;
    
    //导入必需的 java 库
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    
    // 扩展 HttpServlet 类
    public class a extends HttpServlet {
     
      private String message;
      private String name;
    
      public void init() throws ServletException
      {
          
          System.out.println("连接数据库...");
          // 执行必需的初始化
          message = "Hello World";
          String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
          String DB_URL = "jdbc:mysql://cdb-4gsyv8oy.bj.tencentcdb.com:10071/rdk";
       
          // 数据库的用户名与密码,需要根据自己的设置
          String USER = "root";
          String PASS = "***********";
          
          
          Connection conn = null;
          Statement stmt = null;
          
          System.out.println("123...");
          try {
            Class.forName("com.mysql.jdbc.Driver");
            // 打开链接
            System.out.println("连接数据库...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            // 执行查询
            System.out.println(" 实例化Statement对象...");
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT id, name, url FROM websites";
            ResultSet rs = stmt.executeQuery(sql);
            
            name = "没有脸上数据库";
            while(rs.next()){
                // 通过字段检索
                int id  = rs.getInt("id");
                name = rs.getString("name");
                String url = rs.getString("url");
    
                // 输出数据
                System.out.print("ID: " + id);
                System.out.print(", 站点名称: " + name);
                System.out.print(", 站点 URL: " + url);
                System.out.print("\n");
            }
            // 完成后关闭
            rs.close();
            stmt.close();
            conn.close();
        } catch (Exception e) {
            System.out.println(" 实例化Statement对象...");
            e.printStackTrace();
        }
      
          
      }
    
      public void doGet(HttpServletRequest request,
                        HttpServletResponse response)
                throws ServletException, IOException
      {
          // 设置响应内容类型
          response.setContentType("text/html");
    
          // 实际的逻辑是在这里
          PrintWriter out = response.getWriter();
          out.println("<h1>" + message + "</h1>");
          out.println("<h1>" + name + "</h1>");
      }
      
      public void destroy()
      {
          // 什么也不做
      }
    }
    

    相关文章

      网友评论

          本文标题:2019-02-20

          本文链接:https://www.haomeiwen.com/subject/vuphyqtx.html