JavaWeb-Mysql 3-5 Mybatis案例3 添加&修改、删除功能

1、添加

在这里插入图片描述
在这里插入图片描述
如上图是我们平时在添加数据时展示的页面,而我们在该页面输入想要的数据后添加 提交 按钮,就会将这些数据添加到数
据库中。接下来我们就来实现添加数据的操作。

1.1 编写接口方法

在这里插入图片描述
参数:除了id之外的所有的数据。id对应的是表中主键值,而主键我们是 自动增长 生成的。

1.2 编写SQL语句

    <insert id="add">
        insert  into tb_brand (brand_name,company_name,ordered,description,status)
        values (#{brandName},#{companyName},#{ordered},#{description},#{status});
    </insert>

在这里插入图片描述

1.3 编写测试方法并执行

@Test
    public void add() throws Exception {
   

        // 0.传参数
        int status = 1;
        String companyName = "波波手机";
        String brandName = "波波";
        String description = "手机中的战斗机";
        int ordered = 100;


        // 封装brand对象
        Brand brand = new Brand();
        brand.setStatus(status);
        brand.setCompanyName(companyName);
        brand.setDescription(description);
        brand.setBrandName(brandName);
        brand.setOrdered(ordered);
        //1、加载mybatis的核心配置文件,获取SqlSessionFactory
        String resource = "mybatis-config.xml";//相对路径,基于resources
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //2.有了工厂对象,就要获取SqlSession对象,执行SQL语句。
        SqlSession sqlSession = sqlSessionFactory.openSession();
         //SqlSession sqlSession = sqlSessionFactory.openSession(true); //设置自动提交事务,这种情况不需要手动提交事务了


        //3.执行sql获取UserMapper接口的代理对象
        BrandMapper brandMapper = sqlSe
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值