java - 如何在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>
解决方案
您需要在连接对象之前加载 MySQL 驱动程序
Class.forName("com.mysql.jdbc.Driver");
推荐阅读
- javascript - 删除 json 对象中的动态不必要属性
- maven - 如何测试 Maven 部署?
- mysql - 如何在 Nestjs 中设置 typeorm 连接池大小?(MySQL)
- javascript - discord.js如何获取公会成员的数量
- flutter - 用于 Google Pay 的 Flutter 应用内购买工具
- c# - 在 Uno 2.4 和 WASM 上进行页面导航后,ProgressRing 停止动画
- ios - 防止观察者收到通知
- javascript - 如何将令牌转换为所需的格式?
- python - 在掩码上求和:只有整数标量数组可以转换为标量索引
- java-8 - Java Map:按键的属性和最大值分组