- Servlet是Java程序,所以在Servlet中完全可以编写JDBC代码连接数据库。
- 在一个webapp中去连接数据库,需要将驱动jar包放到WEB-INF/lib目录下。(com.mysql.cj.jdbc.Driver 这个类就在驱动jar包当中。)
代码如下:
package com.north.javaweb.servlet;
import jakarta.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
public class StudentServlet implements Servlet {
@Override
public void init(ServletConfig servletConfig) throws ServletException {
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
// 设置相应的内容类型
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// 连接数据库
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// 注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 获取连接
String url = "jdbc:mysql://localhost:3306/north";
String user = "root";
String password = "123456";
// 获取预编译数据库操作对象
connection = DriverManager.getConnection(url, user, password);
String sql = "select name from user";
preparedStatement = connection.prepareStatement(sql);
// 执行sql
resultSet = preparedStatement.executeQuery();
// 处理结果集
while (resultSet.next()) {
String name = resultSet.getString("name");
out.println(name + "<br>");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 释放资源
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
}
}
标签:String,数据库,resultSet,public,connection,null,Servlet,连接
From: https://www.cnblogs.com/NorthPoet/p/17376890.html