1、怎么做?

  • 在Servlet中直接编写Java代码即可(JDBC)
  • 需要将驱动jar包拷贝到webapps\crm\WEB-INF\lib目录下

    2、实现连接数据库

    ```java package Servlet;

/**

  • @Author: 小雷学长
  • @Date: 2022/3/16 - 10:06
  • @Version: 1.8 */

import jakarta.servlet.Servlet; import jakarta.servlet.ServletException; import jakarta.servlet.*;

import java.io.IOException;

import java.io.IOException; import java.io.PrintWriter; import java.sql.*;

public class StudentServlet implements Servlet {

  1. public void init(ServletConfig config)
  2. throws ServletException {
  3. }
  4. public void service(ServletRequest request, ServletResponse response)
  5. throws ServletException, IOException {
  6. /*
  7. 打印到浏览器上
  8. */
  9. response.setContentType("text/html");
  10. //返回out
  11. PrintWriter out = response.getWriter();
  12. /*
  13. 编写JDBC代码,连接数据,查询所有信息
  14. */
  15. Connection conn = null;
  16. PreparedStatement ps = null;
  17. ResultSet rs = null;
  18. try {
  19. //注册驱动
  20. Class.forName("com.mysql.cj.jdbc.Driver");
  21. //获取连接
  22. String url = "jdbc:mysql://localhost:3306/practice";
  23. String user = "root";
  24. String password = "123456";
  25. conn = DriverManager.getConnection(url, user, password);
  26. //获取预编译的数据库操作对象
  27. String sql = "select id,informant_name from t_student";
  28. ps = conn.prepareStatement(sql);
  29. //执行SQL
  30. rs = ps.executeQuery();
  31. //处理查询结果集
  32. while (rs.next()) {
  33. String id = rs.getString("id");
  34. String informant_name = rs.getString("informant_name");
  35. //打印out
  36. out.print(id + "," + informant_name + "<br>");
  37. }
  38. } catch (Exception e) {
  39. e.printStackTrace();
  40. } finally {
  41. //释放资源
  42. if (rs != null) {
  43. try {
  44. rs.close();
  45. } catch (Exception e) {
  46. e.printStackTrace();
  47. }
  48. }
  49. if (ps != null) {
  50. try {
  51. ps.close();
  52. } catch (Exception e) {
  53. e.printStackTrace();
  54. }
  55. }
  56. if (conn != null) {
  57. try {
  58. conn.close();
  59. } catch (Exception e) {
  60. e.printStackTrace();
  61. }
  62. }
  63. }
  64. }
  65. public void destroy() {
  66. }
  67. public String getServletInfo() {
  68. return "";
  69. }
  70. public ServletConfig getServletConfig() {
  71. return null;
  72. }

}

```