Servlet中编写JDBC程序连接数据库

一、怎么做?

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

二、实现连接数据库

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