JDBC练习-添加

 

 

  /*
     * 添加
     * 1.insert into tb_ brand(brand_ name, company_ name, ordered, description, status) values(?,?,?,?,?);
     * 2.参数:需要id之外所有参数信息
     * 3.结果:boolean
     * */
    @Test
    public void testBrand1() throws Exception {
        //模拟用户输入内容
        String brandName="香飘飘";
        String companyName="香飘飘有限公司";
        int ordered=1;
        String description="绕地球一圈";
        int status=1;
        //1.导入jar包
        //2.定义配置文件
        //3.加载配置文件
        Properties prop = new Properties();
        //获取数据库的位置信息,加载数据库
        prop.load(new FileInputStream("F:\\Develop\\code\\Demo2\\src\\druid.txt"));
        //4.获取连接池对象
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
        //5.获取数据库连接Connection
        Connection connection = dataSource.getConnection();
        //6.定义SQL
        String sql="insert into tb_brand(brand_name, company_name, ordered, description, status) values(?,?,?,?,?)";
        //7.获取pstmt对象
        PreparedStatement pstmt = connection.prepareStatement(sql);
        //8.设置参数
        pstmt.setString(1,brandName);
        pstmt.setString(2,companyName);
        pstmt.setInt(3,ordered);
        pstmt.setString(4,description);
        pstmt.setInt(5,status);
        //9.执行sql
        int update = pstmt.executeUpdate();//返回受影响行数
        //10.判断返回值
        if (update>0){
            System.out.println("执行成功");
        }else {
            System.out.println("执行失败");
        }
        //11.释放资源
        connection.close();
        pstmt.close();
    }

 

posted @ 2023-06-15 16:48  Karlshell  阅读(8)  评论(0)    收藏  举报