【Java】JDBC练习

发布时间:2024年01月20日

JDBC练习

环境准备

-- 删除tb_brand表
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;
package pojo;

public class Brand {
    private Integer id; // 主键
    private String brandName; // 品牌名称
    private String companyName; // 企业名称
    private Integer ordered; // 排序字段
    private String description; // 描述信息
    private Integer status; // 状态

    public Brand() {}

    public Brand(Integer id, String brandName, String companyName, Integer ordered, String description, Integer status) {
        this.id = id;
        this.brandName = brandName;
        this.companyName = companyName;
        this.ordered = ordered;
        this.description = description;
        this.status = status;
    }

    // Getter and Setter methods
    public Integer getId() {
        return id;
    }

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

    public String getBrandName() {
        return brandName;
    }

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

    public String getCompanyName() {
        return companyName;
    }

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

    public Integer getOrdered() {
        return ordered;
    }

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

    public String getDescription() {
        return description;
    }

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

    public Integer getStatus() {
        return status;
    }

    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 +
                '}';
    }
}

查询所有数据

package example;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import pojo.Brand;

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

public class BrandTest {
    //查询所有:select * from tb_brand
    public static void main(String[] args) throws Exception {
        //1.获取连接Connection对象
        Properties prop=new Properties();
        prop.load(new FileInputStream("C:\\Users\\Hayaizo\\IdeaProjects\\jdbc\\jdbc_test\\src\\druid.properties"));
        //获取连接池对象
        DataSource dataSource= DruidDataSourceFactory.createDataSource(prop);
        Connection connection=dataSource.getConnection();

        //定义sql语句
        String sql="select * from tb_brand";

        //获取pstmt对象
        PreparedStatement pstmt=connection.prepareStatement(sql);

        //设置参数

        //执行SQL
        ResultSet rs=pstmt.executeQuery();

        //处理结果 List<Brand>封装Brand对象
        List<Brand> list=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=new Brand();
            brand.setId(id);
            brand.setBrandName(brandName);
            brand.setCompanyName(companyName);
            brand.setOrdered(ordered);
            brand.setDescription(description);
            brand.setStatus(status);

            //装载集合
            list.add(brand);
        }

        System.out.println(list);

        //释放资源
        rs.close();
        pstmt.close();
        connection.close();

    }
}

添加&修改&删除

package example;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import pojo.Brand;

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

public class BrandTest {
    //查询所有:select * from tb_brand
    public static void main(String[] args) throws Exception {
        //1.获取连接Connection对象
        Properties prop=new Properties();
        prop.load(new FileInputStream("C:\\Users\\Hayaizo\\IdeaProjects\\jdbc\\jdbc_test\\src\\druid.properties"));
        //获取连接池对象
        DataSource dataSource= DruidDataSourceFactory.createDataSource(prop);
        Connection connection=dataSource.getConnection();
        connection.setAutoCommit(false);

        //定义sql语句
        String sql="insert into tb_brand(brand_name,company_name,ordered,description,status) values (?,?,?,?,?)";
        String brand_name="香飘飘1";
        String company_name="香飘飘1";
        int ordered=10;
        String description="香飘飘企业1";
        int status=0;

        //获取pstmt对象
        PreparedStatement pstmt=connection.prepareStatement(sql);


        //设置参数
        pstmt.setString(1,brand_name);
        pstmt.setString(2,company_name);
        pstmt.setInt(3,ordered);
        pstmt.setString(4,description);
        pstmt.setInt(5,status);

        int res= 0;
        try {
            res = pstmt.executeUpdate();
            connection.commit();
        } catch (Exception e) {
            connection.rollback();
            throw new RuntimeException(e);
        }

        if(res!=0){
            System.out.println("添加成功");
        }else{
            System.out.println("添加失败");
        }

        //释放资源
        pstmt.close();
        connection.close();

    }
}

文章来源:https://blog.csdn.net/2301_79516932/article/details/135718046
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。