2024考古之还在用原始JDBC开发 手搓 案例 实现一个模块的增删改

news2024/10/22 12:49:45

JDBC案例

将来如果完成的话

就代表对JDBC里面的知识点全部融会贯通了

其实就是对数据的增删改查

我们入门做不出来前端的内容

很正常

准备环境

建表

use mybatis;

create table tbl_brand
(
    id int primary key auto_increment,

    brand_name varchar(20),

    company_name varchar(20),

    ordered int ,

    description varchar(100),

    staus int

);

insert into tbl_brand(brand_name, company_name, ordered, description, staus)
values ('三只松鼠','三只松鼠股份有限公司',5,'好吃不上火',0),
       ('华为','华为技术有限公司',100,'华为致力于把数字世界带给每个人','1'),
       ('小米','小米科技有限公司',50,'are you ok',1);

SELECT * from tbl_brand;

创建实体类

封装实体类

package pojo;

public class Brand {
    private Integer id;
    private String brandName;
    private String companyName;
    private String ordered;
    private String description;
    private String status;

    public Brand() {
    }

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

    /**
     * 获取
     * @return id
     */
    public Integer getId() {
        return id;
    }

    /**
     * 设置
     * @param id
     */
    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * 获取
     * @return brandName
     */
    public String getBrandName() {
        return brandName;
    }

    /**
     * 设置
     * @param brandName
     */
    public void setBrandName(String brandName) {
        this.brandName = brandName;
    }

    /**
     * 获取
     * @return companyName
     */
    public String getCompanyName() {
        return companyName;
    }

    /**
     * 设置
     * @param companyName
     */
    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    /**
     * 获取
     * @return ordered
     */
    public String getOrdered() {
        return ordered;
    }

    /**
     * 设置
     * @param ordered
     */
    public void setOrdered(String ordered) {
        this.ordered = ordered;
    }

    /**
     * 获取
     * @return description
     */
    public String getDescription() {
        return description;
    }

    /**
     * 设置
     * @param description
     */
    public void setDescription(String description) {
        this.description = description;
    }

    /**
     * 获取
     * @return status
     */
    public String getStatus() {
        return status;
    }

    /**
     * 设置
     * @param status
     */
    public void setStatus(String status) {
        this.status = status;
    }

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

在实体类当中

基本数据类型建议使用对应的包装类

写测试用例

我们的测试类是放在example包下的

我们要做的是查询 添加 修改 删除 这四个功能

我们在之前学习到的

我们的JDBC写代码 都是7步

我们首先得写一个配置类

目的是获取数据库的连接

package config;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.util.Properties;

public class GetConnection {
    public static Connection getConnection() throws Exception {

        //加载配置文件
        Properties prop=new Properties();
        prop.load(new FileInputStream("JDBC/druid.properties"));

        //获取连接池对象
        DataSource dataSource=DruidDataSourceFactory.createDataSource(prop);

        //获取数据库连接 Connection
        Connection connection=dataSource.getConnection();

        return connection;

    }
}

但是由于路径的缘故

我们把他写在测试里面

我们首先思考如何书写SQL;语句

然后获取连接

然后执行就行了

package example;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import org.junit.Test;
import pojo.Brand;

import javax.sql.DataSource;
import java.io.FileInputStream;
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 {

    @Test
    public void testSelectAll() throws Exception {

        System.out.println(System.getProperty("user.dir"));

        //获取连接
        Properties prop=new Properties();
        prop.load(new FileInputStream("src\\druid.properties"));

        //获取连接池对象
        DataSource dataSource= DruidDataSourceFactory.createDataSource(prop);

        //获取数据库连接 Connection
        Connection connection=dataSource.getConnection();

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

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

        //设置参数

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

        //处理结果 List<Brand> 封装brand对象 装载List集合
        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 stauts = rs.getInt("status");
            //封装Brand对象
            Brand brand=new Brand(id,brandName,companyName,ordered,description,stauts);
            //装载集合
            brands.add(brand);
        }

        //打印集合
        for (Brand brand : brands) {
            System.out.println(brand);
        }

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

    }

}

测试通过

添加数据

我们查看一下页面原型

我们代码接收一个insert语句

插入数据就行

我们要插入除了id外的所有数据

id为递增且唯一

我们还是用PreparedStatement对象接收

我们以后在开发JDBC程序的时候

要注意三个事情

一个是SQL语句怎么书写

然后是要填入的参数

然后是返回值

例如这边的添加操作

package example;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import org.junit.Test;
import pojo.Brand;

import javax.sql.DataSource;
import java.io.FileInputStream;
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 TestAdd {

    @Test
    public void testSelectAll() throws Exception {

        //模拟接收页面提交的数据
        String brandName="香飘飘";
        String companyName="香飘飘";
        int ordered=1;
        String description="绕地球一圈";
        int status=1;

        //insert into tbl_brand(brand_name,company_name,ordered,description,status) values(?,?,?,?,?);
        //参数 需要 除了id之外的所有参数信息
        //返回值 boolean

        System.out.println(System.getProperty("user.dir"));

        //获取连接
        Properties prop=new Properties();
        prop.load(new FileInputStream("src\\druid.properties"));

        //获取连接池对象
        DataSource dataSource= DruidDataSourceFactory.createDataSource(prop);

        //获取数据库连接 Connection
        Connection connection=dataSource.getConnection();

        //定义sql语句
        String sql = "insert into tbl_brand(brand_name,company_name,ordered,description,status) values(?,?,?,?,?);";

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

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

        //执行sql
        int count=pstmt.executeUpdate();  //影响的行数

        //处理结果
        System.out.println(count>0);

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

    }

}

添加成功

修改数据

我们只是换了个SQL数据模型

和参数

即可

代码

package example;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import org.junit.Test;
import pojo.Brand;

import javax.sql.DataSource;
import java.io.FileInputStream;
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 TestUpdate {

    @Test
    public void testUpdate() throws Exception {

        //模拟接收页面提交的数据
        String brandName="香飘飘";
        String companyName="香飘飘";
        int ordered=1;
        String description="绕地球三圈";
        int status=1;
        int id=1;

        //update tbl_brand set brand_name = ?,company_name=?,ordered=?,description=?,status=? where id =? ;
        //参数 需要 所有参数信息
        //返回值 boolean

        System.out.println(System.getProperty("user.dir"));

        //获取连接
        Properties prop=new Properties();
        prop.load(new FileInputStream("src\\druid.properties"));

        //获取连接池对象
        DataSource dataSource= DruidDataSourceFactory.createDataSource(prop);

        //获取数据库连接 Connection
        Connection connection=dataSource.getConnection();

        //定义sql语句
        String sql = "update tbl_brand set brand_name = ?,company_name=?,ordered=?,description=?,status=? where id =? ;";

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

        //设置参数
        pstmt.setString(1,brandName);
        pstmt.setString(2,companyName);
        pstmt.setInt(3,ordered);
        pstmt.setString(4,description);
        pstmt.setInt(5,status);
        pstmt.setInt(6,id);

        //执行sql
        int count=pstmt.executeUpdate();  //影响的行数

        //处理结果
        System.out.println(count>0);

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

    }

}

执行成功

瞅一眼数据库

成功修改

删除数据

不解释了

直接灵魂三问

改一下sql语句和获取PreparedStatement对象的参数即可

执行代码

package example;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import org.junit.Test;
import pojo.Brand;

import javax.sql.DataSource;
import java.io.FileInputStream;
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 TestDelete {

    @Test
    public void testDelete() throws Exception {

        //模拟接收页面提交的数据
        int id=1;

        //delete from tbl_brand where id= ?
        //参数 需要id
        //返回值 boolean

        System.out.println(System.getProperty("user.dir"));

        //获取连接
        Properties prop=new Properties();
        prop.load(new FileInputStream("src\\druid.properties"));

        //获取连接池对象
        DataSource dataSource= DruidDataSourceFactory.createDataSource(prop);

        //获取数据库连接 Connection
        Connection connection=dataSource.getConnection();

        //定义sql语句
        String sql = "delete from tbl_brand where id= ?";

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

        //设置参数
        pstmt.setInt(1,id);

        //执行sql
        int count=pstmt.executeUpdate();  //影响的行数

        //处理结果
        System.out.println(count>0);

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

    }

}

删除成功

数据库中的数据成功删除

个人号推广

博客主页

多多!-CSDN博客

Web后端开发

https://blog.csdn.net/qq_30500575/category_12624592.html?spm=1001.2014.3001.5482

Web前端开发

https://blog.csdn.net/qq_30500575/category_12642989.html?spm=1001.2014.3001.5482

数据库开发

https://blog.csdn.net/qq_30500575/category_12651993.html?spm=1001.2014.3001.5482

项目实战

https://blog.csdn.net/qq_30500575/category_12699801.html?spm=1001.2014.3001.5482

算法与数据结构

https://blog.csdn.net/qq_30500575/category_12630954.html?spm=1001.2014.3001.5482

计算机基础

https://blog.csdn.net/qq_30500575/category_12701605.html?spm=1001.2014.3001.5482

回忆录

https://blog.csdn.net/qq_30500575/category_12620276.html?spm=1001.2014.3001.5482

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1844262.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

在hue中使用ooize调度ssh任务无法执行成功,无法查看错误

ssh执行失败&#xff0c;但是hue没有给出明确的错误原因&#xff1a; 经过经验分析&#xff0c;原来是服务器上的sh文件用的是doc/window格式&#xff0c;需要使用notepad将格式改为unix之后就可以正常执行。 特此记录&#xff0c;避免遗忘知识点

图标设计新手手册:应用图标尺寸比例全解析

通常我们在App Store中寻找新的应用程序时&#xff0c;首先会快速扫描搜索栏中的一些关键词&#xff0c;然后选择感兴趣的应用程序&#xff0c;在选定的应用页面中查看具体信息&#xff0c;最后决定是否下载。在这一系列操作中&#xff0c;APP图标的大小比例是影响用户体验的关…

大腾智能,基于云原生的国产工业协同平台

大腾智能是一家基于云原生的国产工业软件与数字化协同平台&#xff0c;专注于推动企业数字化转型与升级&#xff0c;为企业提供一系列专业、高效的云原生数字化软件及方案&#xff0c;推动产品设计、生产及营销展示的革新&#xff0c;实现可持续发展。 大腾智能旗下产品 3D模型…

前端构建工具用得好,构建速度提升 10 倍

今天来盘点一下前端构建工具。 Turbopack Turbopack&#xff0c;由Vercel开源&#xff0c;是下一代高性能的JavaScript应用构建工具&#xff0c;目前用于 Next.js 中。Turbopack旨在通过革新JavaScript应用的打包流程来显著提升应用性能&#xff0c;它专注于缩短加载时间&…

小阿轩yx-Tomcat 部署及优化

小阿轩yx-Tomcat 部署及优化 Tomcat 概述 免费的、开放源代码的Web应用服务器Apache软件基金会(Apache Software Foundation)Jakarta项目中的一个核心项目由Apache、Sun和一些公司及个人共同开发而成深受Java爱好者的喜爱,并得到部分软件开发商的认可目前比较流行的Web应用服…

强化学习——基本概念

何为强化学习 机器学习的一大分支 强化学习&#xff08;Reinforcement Learning&#xff09;是机器学习的一种&#xff0c;它通过与环境不断地交互&#xff0c;借助环境的反馈来调整自己的行为&#xff0c;使得累计回报最大。强化学习要解决的是决策问题——求取当前状态下最…

sql资料库

1、distinct(关键词distinct用于返回唯一不同的值)&#xff1a;查询结果中去除重复行的关键字 select distinct(university) from user_profile select distinct university from user_profile distinct是紧跟在select后面的&#xff0c;不能在其他位置&#xff0c;不然就…

充电学习— 9、Typec Pd

GND&#xff1a;线缆接地 TX RX&#xff1a;数据流data传输&#xff0c;支持2.0 3.0 speed兼容 VBUS&#xff1a;线缆cable电源&#xff0c;bus power CC&#xff1a;电缆cable的连接、方向、角色检测和当前模式的配置通道&#xff1b; 有emark时&#xff0c; 一个成为VCONN&am…

Flutter【组件】按钮

简介 flutter 按钮组件。提供一种封装按钮组件的思路&#xff0c;并不支持过多的自定义属性。根据使用场景及设计规范进行封装&#xff0c;使用起来比较方便。 github地址&#xff1a;https://github.com/ThinkerJack/jac_uikit pub地址&#xff1a;https://pub.dev/package…

【2024最新华为OD-C/D卷试题汇总】[支持在线评测] 密码解密(100分) - 三语言AC题解(Python/Java/Cpp)

&#x1f36d; 大家好这里是清隆学长 &#xff0c;一枚热爱算法的程序员 ✨ 本系列打算持续跟新华为OD-C/D卷的三语言AC题解 &#x1f4bb; ACM银牌&#x1f948;| 多次AK大厂笔试 &#xff5c; 编程一对一辅导 &#x1f44f; 感谢大家的订阅➕ 和 喜欢&#x1f497; &#x1f…

【多模态论文】CLIP(Contrastive Language-Image Pre-training)

论文&#xff1a;Learning Transferable Visual Models From Natural Language Supervision 链接&#xff1a;https://arxiv.org/abs/2103.00020 摘要 问题&#xff1a; 对预定的类别进行预测&#xff0c;这种有监督的训练形式受限于额外标记数据 。如何利用图像的原始文本来获…

MEME使用-motif分析(生物信息学工具-24)

01 背景 Motif分析是一种在生物信息学和计算生物学中广泛应用的技术&#xff0c;用于识别DNA、RNA或蛋白质序列中具有生物学功能的短保守序列模式&#xff08;motif&#xff09;。这些motif通常与特定的生物学功能相关&#xff0c;如DNA中的转录因子结合位点、RNA中的剪接位点…

VSCode调试python没有反应

原因&#xff1a;python的版本太低了&#xff0c;我的项目的python是3.5的&#xff0c;VSCode python debugger不支持低版本的python。 解决方法&#xff1a; debugging - debug python versions < 3.5 with vscode new debugger - Stack Overflow 安装支持低版本的Debug…

项目八 OpenStack存储管理

任务一 理解OpenStack块存储服务 1.1 •Cinder的主要功能 • 提供 持久性块存储资源&#xff0c;供 Nova 计算服务的虚拟机实例使用 。 • 为 管理块存储设备提供一套方法&#xff0c;对卷实现从创建到删除的整个生命周期 管理。 • 将 不同的后端存储进行封装&#xff0c;对外…

ScheduledExecutorService引起的线上问题(抛出异常后不继续执行)

线上有一个服务&#xff0c;采用ScheduledExecutorService定时任务刷新数据库数据到本地缓存作为路由信息 private ScheduledExecutorService scheduledExecutorService Executors.newScheduledThreadPool(1);scheduledExecutorService.scheduleWithFixedDelay(new Runnable()…

electron下载失败(electron如何切换镜像源)

打开&#xff1a; 或者&#xff1a; C:\Users\用户名\.npmrc 添加&#xff1a; electron_mirrorhttps://npmmirror.com/mirrors/electron/ 到文件中&#xff0c;保存 方法二&#xff1a; npm config set ELECTRON_MIRROR https://npmmirror.com/mirrors/electron/ ELECTR…

MavenPlus插件的基础功能完善

本次更新主要是在初版的searchEverywhere的基础上增加了pom.xml文件编辑器&#xff0c;目前的界面布局如下&#xff0c;进行适当说明&#xff1a; 打开pom文件后&#xff0c;你会得到如上图所示的布局页面&#xff0c;数据会同步显示 如果有冲突信息&#xff0c;则会以红色显示…

如何解决资源管理器被结束任务后的问题,怎么重启或新建资源管理器任务?

服务器上运行的东西太多&#xff0c;修改个文件夹的名字导致卡死。结束任务后导致系统页面空白。&#xff08;关闭了windows资源管理器&#xff09; 按CtrlShiftDelete没有反应。 按CtrlShiftEsc没有反应。 按CtrlShiftEnd没有反应。 按CtrlALTEnd有反应。 (win2012) 输入…

华为数通——单臂路由

单臂路由&#xff1a;指在三层设备路由器的一个接口上通过配置子接口&#xff08;或“逻辑接口”&#xff0c;并不存在真正物理接口&#xff09;的方式&#xff0c;实现原来相互隔离的不同VLAN&#xff08;虚拟局域网&#xff09;之间的互联互通。但是仅仅允许单播通信。 单臂路…

爬取CSDN博文到本地(包含图片,标签等信息)

文章目录 csdnToMD改进将CSDN文章转化为Markdown文档那有什么办法快速得到md文档&#xff1f;例如&#xff1a;获取单个文章markdown获取所有的文章markdown 项目中待解决的问题 csdnToMD 项目原作者&#xff1a;https://gitee.com/liushili888/csdn-is—mark-down 改进后仓库…