JavaWeb 连接 MySQL 数据库并显示数据库中的内容

时间:2025-01-20 07:38:35
package com.example.demo1; import java.io.*; import java.sql.*; import jakarta.servlet.http.*; import jakarta.servlet.annotation.*; @WebServlet(name = "helloServlet", value = "/hello-servlet") public class HelloServlet extends HttpServlet { private String message; public void init() { message = "Hello World!"; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { // ("text/html"); // 这一段主要是将数据库取出来的数据转成中文(如果确定不会有问题可直接用上面句进行替换) response.setContentType("text/html; charset=UTF-8"); response.setHeader("ContentType","text/html; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); // 数据库连接地址--studtwork 是我创建的一个表 String url = "jdbc:mysql://localhost:3306/studtwork?useSSL=false"; // Mysql 登录用户名 String user = "root"; // Mysql 登录密码 String password = "MySQL123456!"; // sql 查询语句 String sql = "Select * from user"; try { // 如果 JDK 版本低于 11 并且运行这个可以试一下低版本驱动引入程序!!! // (""); Class.forName(""); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } try { Connection conn = DriverManager.getConnection(url, user, password); // 获取数据库操作对象 Statement statement = conn.createStatement(); // 执行 sql 语句 ResultSet res = statement.executeQuery(sql); // 在移动到有数据时返回结果为 true,没有数据则为 false; while (res.next()) { // getString 属性名 String userName = res.getString("userName"); out.println(userName); } } catch (SQLException e) { throw new RuntimeException(e); } out.println("<html><body>"); out.println("<h1>" + message + "</h1>"); out.println("</body></html>"); } public void destroy() { } }