一: 要对数据库内的数据进行增删改查,首先我们需要连接到数据库
1)为了方便我们可以把jdbc代码写到一个Utils工具类内
package westos;
import java.sql.*;
public class Utils {
//这里的b是指你要查询的表名
static final String URL = "jdbc:mysql://localhost:3306/b?serverTimezone=GMT%2B8&useSSL=false" +
"&useServerPrepStmts=true&cachePrepStmts=true&rewriteBatchedStatements=true" +
"&useCursorFetch=true&defaultFetchSize=100&allowPublicKeyRetrieval=true";
//数据库用户名
static final String USERNAME = "root";
//数据库密码
static final String PASSWORD = "itcast";
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
return conn;
}
public static void close(ResultSet rs, PreparedStatement stmt, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(PreparedStatement stmt, Connection conn) {
close(null, stmt, conn);
}
}
二:写好工具类后就可以写增删改查的代码了
增
@WebServlet(urlPatterns = "/insert")
public class Insert extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
//req.getRequestDispatcher("login.jsp").forward(req,resp);
// 获取部门编号
String deptno = req.getParameter("deptno");
int no = Integer.parseInt(deptno);
// 获取部门名称
String dname = req.getParameter("dname");
// 获取地区
String loc = req.getParameter("loc");
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = Utils.getConnection();
stmt = conn.prepareStatement(
"insert into dept(deptno,dname,loc) values(?,?,?)");
stmt.setInt(1, no);
stmt.setString(2, dname);