首页 > 其他分享 >周六 jdbc练习 商品品牌数据增删改查

周六 jdbc练习 商品品牌数据增删改查

时间:2023-07-22 17:55:27浏览次数:29  
标签:jdbc ordered String brand 改查 sql 增删 psmt id

先把练习用的表建立出来

drop table if exists tb_brand;
-- 创建tb_brand表
create table tb_brand
(
    -- id 主键
    id           int primary key auto_increment,
    -- 品牌名称
    brand_name   varchar(20),
    -- 企业名称
    company_name varchar(20),
    -- 排序字段
    ordered      int,
    -- 描述信息
    description  varchar(100),
    -- 状态:0:禁用  1:启用
    status       int
);
-- 添加数据
insert into tb_brand (brand_name, company_name, ordered, description, status)
values ('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
       ('华为', '华为技术有限公司', 100, '华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界', 1),
       ('小米', '小米科技有限公司', 50, 'are you ok', 1);


SELECT * FROM tb_brand;

然后是主类Brand

package pojo;

/**
 * 品牌
 */
public class Brand {
    private Integer id;
    // 品牌名称
    private String brandName;
    // 企业名称
    private String companyName;
    // 排序字段
    private Integer ordered;
    // 描述信息
    private String description;
    // 状态:0:禁用  1:启用
    private Integer  status;

    public Integer getId() {
        return id;
    }

    public String getBrandName() {
        return brandName;
    }

    public String getCompanyName() {
        return companyName;
    }

    public Integer getOrdered() {
        return ordered;
    }

    public String getDescription() {
        return description;
    }

    public Integer getStatus() {
        return status;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public void setBrandName(String brandName) {
        this.brandName = brandName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    public void setOrdered(Integer ordered) {
        this.ordered = ordered;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return "Brand{" +
                "id=" + id +
                ", brandName='" + brandName + '\'' +
                ", companyName='" + companyName + '\'' +
                ", ordered=" + ordered +
                ", description='" + description + '\'' +
                ", status=" + status +
                '}';
    }
}

之后为了方便测试,整了一下junit,然后就可以敲主要内容了

package example.example;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.junit.jupiter.api.Test;
import pojo.Brand;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;

/**
 * 品牌数据增删改查
 */
public class Brandtest {
    /**
     * 查询所有
     * 1.sql:select * from tb_brand
     * 2.参数:不需要
     * 3.结果:list<Brand>
     */
    @Test
    public void testSelectall() throws Exception {
        //1.获取connection
        Properties prop=new Properties();
        prop.load(new FileInputStream("D:\\66\\jdbc_demo\\src\\druid.properties"));
        DataSource dataSource= DruidDataSourceFactory.createDataSource(prop);
        Connection conn=dataSource.getConnection();
        //2.定义sql
        String sql="select * from tb_brand";
        PreparedStatement psmt =conn.prepareStatement(sql);
        //4.设置参数
        //5.执行sql
        ResultSet rs =psmt.executeQuery();
        //6.处理结果 list<Brand>
        Brand brand=new Brand();
        List<Brand> brands=new ArrayList<>();
        while (rs.next()){
            //获取数据
            int id = rs.getInt("id");
            String brandName = rs.getString("brand_name");
            String companyName = rs.getString("company_name");
            int ordered = rs.getInt("ordered");
            String description = rs.getString("description");
            int status = rs.getInt("status");
            //封装Brand对象
            brand.setId(id);
            brand.setBrandName(brandName);
            brand.setCompanyName(companyName);
            brand.setDescription(description);
            brand.setStatus(status);
            brand.setOrdered(ordered);
            //装载集合
            brands.add(brand);
        }
        //7.释放资源
        rs.close();
        psmt.close();
        conn.close();

        System.out.println(brands);

    }


    /**
     * 添加
     * 1.sql:insert into tb_brand(brand_name, company_name, ordered, description, status) values (?,?,?,?,?);
     * 2.参数:除了id之外所有信息
     * 3.结果:boolean
     */
    @Test
    public void testadd() throws Exception {
        //模拟获取参数
        String brandName="theshy";
        String companyName="wbg";
        int ordered=1;
        String  description="别吃,别吃";
        int status=1;
        //1.获取connection
        Properties prop=new Properties();
        prop.load(new FileInputStream("D:\\66\\jdbc_demo\\src\\druid.properties"));
        DataSource dataSource= DruidDataSourceFactory.createDataSource(prop);
        Connection conn=dataSource.getConnection();
        //2.定义sql
        String sql="insert into tb_brand(brand_name, company_name, ordered, description, status) values (?,?,?,?,?);";
        PreparedStatement psmt =conn.prepareStatement(sql);
        //4.设置参数
        psmt.setString(1,brandName);
        psmt.setString(2,companyName);
        psmt.setInt(3,ordered);
        psmt.setString(4,description);
        psmt.setInt(5,status);
        //5.执行sql
        int count=psmt.executeUpdate();//影响的行数
        //6.处理结果
        System.out.println(count>0);

        //7.释放资源
        psmt.close();
        conn.close();


    }



     /**
     * 修改
     * 1.sql:update tb_brand
      * set brand_name=?,
      *     company_name=?,
      *     ordered=?,
      *     description=?,
      *     status=?
      * where id=?;
     * 2.参数:需要所有数据
     * 3.结果:boolean
     */
    @Test
    public void testupdate() throws Exception {
        String brandName="theshy";
        String companyName="wbg";
        int ordered=1000;
        String  description="别吃,别吃";
        int status=1;
        int id=4;
        //1.获取connection
        Properties prop=new Properties();
        prop.load(new FileInputStream("D:\\66\\jdbc_demo\\src\\druid.properties"));
        DataSource dataSource= DruidDataSourceFactory.createDataSource(prop);
        Connection conn=dataSource.getConnection();
        //2.定义sql
        String sql="update tb_brand\n" +
                "set brand_name=?,\n" +
                "    company_name=?,\n" +
                "    ordered=?,\n" +
                "    description=?,\n" +
                "    status=?\n" +
                "where id=?;";
        PreparedStatement psmt =conn.prepareStatement(sql);
        //4.设置参数
        psmt.setString(1,brandName);
        psmt.setString(2,companyName);
        psmt.setInt(3,ordered);
        psmt.setString(4,description);
        psmt.setInt(5,status);
        psmt.setInt(6,id);
        //5.执行sql
        int count=psmt.executeUpdate();//影响的行数
        //6.处理结果
        System.out.println(count>0);

        //7.释放资源
        psmt.close();
        conn.close();


    }



    /**
     * 删除
     * 1.sql:delete from tb_brand where id=?;
     * 2.参数:需要id
     * 3.结果:boolean
     */
    @Test
    public void testdelete() throws Exception {
        int id=4;
        //1.获取connection
        Properties prop=new Properties();
        prop.load(new FileInputStream("D:\\66\\jdbc_demo\\src\\druid.properties"));
        DataSource dataSource= DruidDataSourceFactory.createDataSource(prop);
        Connection conn=dataSource.getConnection();
        //2.定义sql
        String sql="delete from tb_brand where id=?;";
        PreparedStatement psmt =conn.prepareStatement(sql);
        //4.设置参数
        psmt.setInt(1,id);
        //5.执行sql
        int count=psmt.executeUpdate();//影响的行数
        //6.处理结果
        System.out.println(count>0);

        //7.释放资源
        psmt.close();
        conn.close();


    }





}

 

标签:jdbc,ordered,String,brand,改查,sql,增删,psmt,id
From: https://www.cnblogs.com/zeyangshuaige/p/17573798.html

相关文章

  • 数据库学习复习随笔(JDBC没保存)
    数据库基础语法SQL常用语句总结-知乎(zhihu.com)链接table1JIONtable2ON链接条件--不加就是自然链接数据表的类型逆向查看语句SHOW逆向查看表的结构DESC数据库引擎--关于数据库引擎/*INNODBMYISM以前使用的*/ MYISAMINNODB事物支持不 数据行锁......
  • Could not get list of tables from database. Probably a JDBC driver problem.
     在用myeclipse8.5M1反向生成代码时报错: Aninternalerroroccurredduring:"GeneratingArtifacts".Couldnotgetlistoftablesfromdatabase.ProbablyaJDBCdriverproblem.  =============================  尝试了更换工作空间、重装myeclipse、更换oracle驱动......
  • JDBC记录
    JDBC连接配置使用JDBC:java数据库连接是一套操作所有关系型数据库的规则(接口)。各个数据库实现该接口,提供驱动jar包;使用JDBC编程,真正执行的代码是驱动jar包中的实现类。JDBC编程步骤:1.注册驱动2.获取连接3.获取数据库操作对象(专门执行sql语句的对象)4.执行sql语句5.处理查询......
  • 记jdbcTemplate使用的一个坑
    1、在使用jdbcTemplate时,语句不能使用select* ,不然可能就是这样的错误:Incorrectcolumncount:expected1,actual62、如果像这样的外层嵌套,应该去掉外层select*,语句:select*from(selectmater_score.mater_noasmaterNo,city,town,mater_score.avgasavgScor......
  • JDBC MYSQL too many connections 解决方法
    显示最大连接数showvariableslike"max_connections";设置最大连接数:setGLOBALmax_connections=1000;查看mysql在关闭一个非交互的连接之前要等待的秒数,默认是28800s也就是一个链接sleep八个小时后才会被mysql“清理”掉。showglobalvariableslike'wait_timeout......
  • SpringBoot + Sharding JDBC 分库分表
    Sharding-JDBC最早是当当网内部使用的一款分库分表框架,到2017年的时候才开始对外开源,这几年在大量社区贡献者的不断迭代下,功能也逐渐完善,现已更名为ShardingSphere,2020年4⽉16日正式成为Apache软件基金会的顶级项目。ShardingSphere-Jdbc定位为轻量级Java框架,在Java的Jdbc层提......
  • jdbc-plus是一款基于JdbcTemplate增强工具包,基于JdbcTemplate已实现分页、多租户、动
    ......
  • 怎样优雅地增删查改(八):按用户关系查询
    @目录原理实现正向用户关系反向用户关系使用测试用户关系(Relation)是描述业务系统中人员与人员之间的关系,如:签约、关注,或者朋友关系。之前我们在扩展身份管理模块的时候,已经实现了用户关系管理,可以查看本系列博文之前的内容。怎样优雅地增删查改(二):扩展身份管理模块原理查询依据......
  • jfinal 框架学习笔记-第三天 Model相关学习--record+Model增删改查的用法(震惊之今日刷
    1.了解了数据库连接池。其中使用最多也是最广泛的是druid数据库连接池也就是阿里云研发的数据库连接池2.ActiveRecord(jFinal的核心技术)+DruidPlugin(数据库连接词,如何与数据库打交道)ActiveRecord:1.Record(记录,相当于一个通用的Model),2.Model(提供日常CRUD的封装)Model示例......
  • 怎样优雅地增删查改(七):按用户查询
    @目录实现使用测试实现定义按用户查询(IUserOrientedFilter)接口publicinterfaceIUserOrientedFilter{publicstringEntityUserIdIdiom{get;}Guid?UserId{get;set;}}EntityUserIdIdiom:语义上的UserId,用于指定业务实体中用于描述“用户Id”字段的名称,......