0
点赞
收藏
分享

微信扫一扫

JDBC操作数据的基本步骤

奋斗De奶爸 2021-09-28 阅读 59
日记本

加载驱动

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

ps: 导入正常的数据库驱动包,笔者这里使用的mysql8的驱动包,如图:


获取连接

Connection connection = DriverManager.getConnection(dbURL, username, password);

ps:获取连接时候,一定要写正确数据库的url,数据库的用户名和密码,如图:


获取PreparedStatement,执行sql语句

//根据sql语句
PreparedStatement p = connection.prepareStatement(sql);
p.execute();

ps: sql语句要写正确,参入参数的时候,注意参数的顺序

 private void addOrUpdate(HttpServletRequest req,
                             HttpServletResponse response) throws Exception {
        String id = req.getParameter("id");

        Map<String, Object> map = new HashMap<String, Object>();
        String sql = null;
        if (null != id && !"".equals(id)) {

            sql = "update [mall].[merchant_tj] set name=?, num=?,position=?,nianx=? where 1=1 and id=?";
        } else {
            id = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 10);
            sql = "insert into [mall].[merchant_tj](name,num,position,nianx,id) values(?,?,?,?,?)";
        }
        p = connection.prepareStatement(sql);
        //设置参数
        p.setString(1, req.getParameter("name"));
        p.setString(2, req.getParameter("num"));
        p.setString(3, req.getParameter("position"));
        p.setString(4, req.getParameter("nianx"));
        p.setString(5, id);
        p.execute();
        p.close();
        response.sendRedirect("/test/myservlet");

    }

返回结果集,处理结果

ResultSet rs = p.getResultSet();
        while (rs.next()) {
//                System.out.println(rs.getString("id"));
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", rs.getInt("id"));
            map.put("number", rs.getString("number"));
            map.put("name", rs.getString("name"));
            map.put("xs", rs.getInt("xs"));
            map.put("credit", rs.getString("credit"));
            map.put("zy", rs.getString("zy"));
            map.put("sxs", rs.getString("sxs"));
            map.put("digit", rs.getString("digit"));
            map.put("way", rs.getString("way"));
            list.add(map);
        }

关闭资源

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //关闭资源,倒关
            try {
                if(rs != null) rs.close();
                if(pstmt != null) pstmt.close();
                if(con != null) con.close();  //必须要关
            } catch (Exception e) {
            }
        }

举报

相关推荐

0 条评论