首页 > 解决方案 > 如何在maven webapp Servlet项目中连接数据库mysql?

问题描述

我已经构建了 maven webapp 项目,我创建了扩展 HttpServlet 的类,这个类连接到数据库 Mysql 并获取记录,所有依赖项我把它们放在 pom.xml 文件中,但不起作用我尝试在主类中运行查询,但它的工作,并且当我在 doGet servlet 方法中放置任何期望连接到数据库的东西时,它也可以工作,到数据库的连接和获取记录在 doGet 中不起作用。你能告诉我为什么不起作用吗?扩展 HttpServlet 的此类:

@WebServlet("/Home")
public class HomeClass extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String url = "jdbc:mysql://localhost:3306/company";
        try {
            Connection connection = DriverManager.getConnection(url,"******","*****");
            Statement statement = connection.createStatement();
            ResultSet set =  statement.executeQuery(("SELECT * FROM `users` "));
            while (set.next()){
                resp.getWriter().append(set.getString("firstname")).append(" ");
            }
        } catch (SQLException throwables) {
               resp.getWriter().append(throwables.getMessage());
        }

    }

}

pom.xml 中的依赖项

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.0</version>
      <scope>provided</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.3</version>
      <scope>provided</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.6</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.23</version>
    </dependency>


  </dependencies>

标签: javamysqlmavenservlets

解决方案


您需要在连接对象之前加载 MySQL 驱动程序

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


推荐阅读