使用Servlet对Mysql数据库表中数据进行增删改查

一: 要对数据库内的数据进行增删改查,首先我们需要连接到数据库

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);
            
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值