当前位置: 首页 > article >正文

软件设计之JDBC(1)

软件设计之JDBC(1)

此篇应在MySQL之后进行学习:
路线图推荐:
【Java学习路线-极速版】【Java架构师技术图谱】
尚硅谷2024最新JDBC教程 | jdbc基础到高级一套通关!

资料可以去尚硅谷官网免费领取

学习内容:

  1. 前言
  2. JDBC
  3. PreparedStatement实现CRUD
  4. 常见问题

1、前言

1、开发Java程序时,数据都是存储在内存中,属于临时存储,当程序停止或重启时,内存中的数据就丢失了
2、因此数据通过I/O技术,存储在本地磁盘中,解决了持久化问题,但是没有结构和逻辑,不方便管理和维护
3、通过关系型数据库,将数据可以按照特定的格式交由数据库管理系统维护。关系型数据库是通过库和表分隔不同的数据,表中数据存储的方式是行和列,区分相同格式不同值的数据。
4、如何通过Java程序对数据库中的数据做增删改查?JDBC

2、JDBC

JDBC概念

JDBC:Java Database Connectivity
JDBC是Java提供的一组独立于任何数据库管理系统的API
Java提供接口规范,后由数据库厂商提供接口的实现
在这里插入图片描述

项目入门

使用select version() from DUAL;语句在Navicat中查看MySQL版本
下载MySQL对应JDBC驱动,下载官网点击此处
找到对应MySQL版本,其中Operating System这里选择Platform independent
下载好的驱动导入到项目里并右键Add as library(具体看视频教程哦)
其中JDK使用的是JDK21

数据库SQL语句创建表

CREATE DATABASE atguigu;
USE atguigu;
CREATE TABLE t_emp
(
  emp_id INT AUTO_INCREMENT COMMENT '员工编号' PRIMARY KEY,
  emp_name VARCHAR(100) NOT NULL COMMENT '员工姓名',
  emp_salary DOUBLE(10,5) NOT NULL COMMENT '员工薪资',
  emp_age INT NOT NULL COMMENT '员工年龄'
);
INSERT INTO t_emp(emp_name,emp_salary,emp_age)
VALUES ('andy',777.77,32),
('大风哥',666.66,41),
('康师傅',111,23),
('Gavin',123,26),
('小鱼儿',123,28);

Java对应语句

package com.atguigu.base;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class JDBCQuick {

    public static void main(String[] args) throws Exception {
        //1 注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2 获取连接对象
        String url = "jdbc:mysql://localhost:3306/atguigu";
        String username = "root";
        String password = "root";
        Connection connection = DriverManager.getConnection(url, username, password);
        //3 获取执行SQL语句对象
        Statement statement = connection.createStatement();
        //4 编写SQL语句,并执行,接收返回的结果集
        String sql = "SELECT emp_id,emp_name,emp_salary,emp_age FROM t_emp";
        ResultSet resultSet = statement.executeQuery(sql);
        //5 处理结果:遍历resultSet结果集
        while(resultSet.next()){
            int empId = resultSet.getInt("emp_id");
            String empName = resultSet.getString("emp_name");
            double empSalary = resultSet.getDouble("emp_salary");
            int empAge = resultSet.getInt("emp_age");
            System.out.println(empId +"\t" + empName + "\t" + empSalary + "\t" + empAge);
        }
        //6 释放资源 先开后关原则
        resultSet.close();
        statement.close();
        connection.close();
    }
}

注册驱动

在这里插入图片描述

Connection

在这里插入图片描述

Statement

在这里插入图片描述

SQL注入攻击问题

当控制台输入 a’ or ‘1’ = ‘1 时候,会把所有数据显示
‘a’ or ‘1’ = ‘1’
因为 在SQL语句中WHERE emp_name = true 时,所有都为真

public class JDBCInjection{
    public static void main(String[] args) throws SQLException {
        //1 注册驱动 可省略
        //2 获取连接对象
        String url = "jdbc:mysql://localhost:3306/atguigu";
        String username = "root";
        String password = "root";
        Connection connection = DriverManager.getConnection(url, username, password);
        //3 获取执行SQL语句对象
        Statement statement = connection.createStatement();
        System.out.println("请输入员工姓名:");
        Scanner scanner = new Scanner(System.in);
        String name = scanner.nextLine();
        //4 编写SQL语句,并执行,接收返回的结果集
        String sql = "SELECT emp_id,emp_name,emp_salary,emp_age FROM t_emp WHERE emp_name = '"+name+"'";
        ResultSet resultSet = statement.executeQuery(sql);
        //5 处理结果:遍历resultSet结果集
        while(resultSet.next()){
            int empId = resultSet.getInt("emp_id");
            String empName = resultSet.getString("emp_name");
            double empSalary = resultSet.getDouble("emp_salary");
            int empAge = resultSet.getInt("emp_age");
            System.out.println(empId +"\t" + empName + "\t" + empSalary + "\t" + empAge);
        }
        //6 释放资源 先开后关原则
        resultSet.close();
        statement.close();
        connection.close();
    }
}

PreparedStatement

在这里插入图片描述

package com.atguigu.base;
import java.sql.*;
import java.util.Scanner;
public class JDBCPrepared {
    public static void main(String[] args) throws SQLException {
        //1 注册驱动 可省略
        //2 获取连接对象
        String url = "jdbc:mysql://localhost:3306/atguigu";
        String username = "root";
        String password = "root";
        Connection connection = DriverManager.getConnection(url, username, password);
        //3 获取执行SQL语句对象
        PreparedStatement preparedStatement = connection.prepareStatement("SELECT emp_id,emp_name,emp_salary,emp_age FROM t_emp WHERE emp_name = ?");
        System.out.println("请输入员工姓名:");
        Scanner scanner = new Scanner(System.in);
        String name = scanner.nextLine();
        //4 为?占位符赋值,并执行SQL语句,接收返回的结果集
        //下标从1开始,此处参数只有一个emp_name
        preparedStatement.setString(1,name);
        ResultSet resultSet = preparedStatement.executeQuery();
        //5 处理结果:遍历resultSet结果集
        while(resultSet.next()){
            int empId = resultSet.getInt("emp_id");
            String empName = resultSet.getString("emp_name");
            double empSalary = resultSet.getDouble("emp_salary");
            int empAge = resultSet.getInt("emp_age");
            System.out.println(empId +"\t" + empName + "\t" + empSalary + "\t" + empAge);
        }
        //6 释放资源 先开后关原则
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }
}

ResultSet

在这里插入图片描述

3、PreparedStatement实现CRUD

前期准备

需要下载junit-4.12.jar 和hamcrest-2.2.jar包导入进项目中
下载地址可以点击此处:
下载链接1对应junit
下载链接2对应hamcrest

单行单列查询

    @Test
    public void testQuerySingleRowAndCol() throws SQLException {
        //1 注册驱动 可省略
        //2 获取连接对象
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/atguigu", "root", "root");
        //3 获取执行SQL语句对象
        PreparedStatement preparedStatement = connection.prepareStatement("SELECT COUNT(*) as count FROM t_emp");
        //4 执行SQL语句,接收返回的结果集
        ResultSet resultSet = preparedStatement.executeQuery();
        //5 处理结果:遍历resultSet结果集
        while(resultSet.next()){
            int count = resultSet.getInt("count");
            System.out.println(count);
        }
        //6 释放资源 先开后关原则
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }

单行多列查询

@Test
    public void testQuerySingleRow() throws SQLException {
        //1 注册驱动 可省略
        //2 获取连接对象
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/atguigu", "root", "root");
        //3 获取执行SQL语句对象
        PreparedStatement preparedStatement = connection.prepareStatement("SELECT emp_id,emp_name,emp_salary,emp_age FROM t_emp WHERE emp_id = ?");
        //4 为?占位符赋值,并执行SQL语句,接收返回的结果集
        preparedStatement.setInt(1,3);
        ResultSet resultSet = preparedStatement.executeQuery();
        //5 处理结果:遍历resultSet结果集
        while(resultSet.next()){
            int empId = resultSet.getInt("emp_id");
            String empName = resultSet.getString("emp_name");
            double empSalary = resultSet.getDouble("emp_salary");
            int empAge = resultSet.getInt("emp_age");
            System.out.println(empId +"\t" + empName + "\t" + empSalary + "\t" + empAge);
        }
        //6 释放资源 先开后关原则
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }

多行多列查询

    @Test
    public void testQueryMoreRow() throws SQLException {
        //1 注册驱动 可省略
        //2 获取连接对象
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/atguigu", "root", "root");
        //3 获取执行SQL语句对象
        PreparedStatement preparedStatement = connection.prepareStatement("SELECT emp_id,emp_name,emp_salary,emp_age FROM t_emp WHERE emp_age > ?");
        //4 为?占位符赋值,并执行SQL语句,接收返回的结果集
        preparedStatement.setInt(1,25);
        ResultSet resultSet = preparedStatement.executeQuery();
        //5 处理结果:遍历resultSet结果集
        while(resultSet.next()){
            int empId = resultSet.getInt("emp_id");
            String empName = resultSet.getString("emp_name");
            double empSalary = resultSet.getDouble("emp_salary");
            int empAge = resultSet.getInt("emp_age");
            System.out.println(empId +"\t" + empName + "\t" + empSalary + "\t" + empAge);
        }
        //6 释放资源 先开后关原则
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }

新增一条数据

 @Test
    public void testInsert() throws SQLException {
        //1 注册驱动 可省略
        //2 获取连接对象
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/atguigu", "root", "root");
        //3 获取执行SQL语句对象
        PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO t_emp(emp_name,emp_salary,emp_age) VALUES (?,?,?)");
        //4 为?占位符赋值,并执行SQL语句,接收返回的结果集
        preparedStatement.setString(1,"Rose");
        preparedStatement.setDouble(2,888.88);
        preparedStatement.setInt(3,28);
        int result = preparedStatement.executeUpdate();
        //5 处理结果:根据受影响的行数做判断,得到成功或失败
        if (result > 0){
            System.out.println("成功");
        }else {
            System.out.println("失败");
        }
        //6 释放资源 先开后关原则
        preparedStatement.close();
        connection.close();
    }

修改一条数据

    @Test
    public void testUpdate() throws SQLException {
        //1 注册驱动 可省略
        //2 获取连接对象
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/atguigu", "root", "root");
        //3 获取执行SQL语句对象
        PreparedStatement preparedStatement = connection.prepareStatement("UPDATE t_emp SET emp_salary = ? WHERE emp_id = ?");
        //4 为?占位符赋值,并执行SQL语句,接收返回的结果集
        preparedStatement.setDouble(1,999.99);
        preparedStatement.setInt(2,6);
        int result = preparedStatement.executeUpdate();
        //5 处理结果:根据受影响的行数做判断,得到成功或失败
        if (result > 0){
            System.out.println("成功");
        }else {
            System.out.println("失败");
        }
        //6 释放资源 先开后关原则
        preparedStatement.close();
        connection.close();
    }

4、常见问题

java.sql.SQLSyntaxErrorException

1、SQL语句有错误,建议SQL语句在SQL工具中测试后再复制到java程序中
2、连接数据库的URL中,数据库名称编写错误

java.sql.SQLException:No value specified parameter 1

在使用预编译SQL时,如果有?占位符,要为每一个占位符赋值,否则报该错误

java.sql.SQLException: Access denied for user ‘root’@‘localhost’(using password: YES)

连接数据库时,如果用户名或密码输入错误,也会报SQLException

CommunicationException:Communication link failure

在连接数据库的URL时,如果IP或端口写错了,会报如下异常


http://www.kler.cn/news/289754.html

相关文章:

  • day06-集合-CollectionListSet
  • 检查linux是否被入侵之计划任务和系统后门
  • 快速排序(动图详解)(C语言数据结构)
  • Ceph RBD使用
  • String核心设计模式——建造者模式
  • 性能工具之 JProfiler 简单登录案例分析实战
  • 网络安全服务基础Windows--第10节-FTP主动与被动模式
  • 【工具篇】vscode设置护眼色主题皮肤
  • JavaScript基础概述
  • 【RabbitMQ】基本概念以及安装教程
  • (C++ STL)list类的简单模拟实现与源码展示
  • 【大模型测评】2024大语言模型综合能力测评报告(免费下载)
  • “三年级英语”暴增5亿搜索量?需求来了!附2个极品AI吸粉玩法!
  • 第3章-04-Python库BeautifulSoup安装与讲解
  • Gateway的基本概念
  • Django + websocket 连不上
  • 内部知识库:企业智慧资产的安全守护者
  • 低秩近似概念
  • Dev C++:简单步骤下载与安装指南
  • DHCPv6 浅析 配置示例
  • 基于vue框架的超市商品管理系统m9o29(程序+源码+数据库+调试部署+开发环境)系统界面在最后面。
  • Redis Desktop Manager 0.8.8.384 安装与使用详解
  • Spire.PDF for .NET【文档操作】演示:创建 PDF 文档
  • python-实战4拆分pdf文件
  • 小土堆pytorch
  • CSS实现水滴效果图
  • 【Linux】进程间的关系(第十三篇)
  • oracle日期加减方式
  • 【区块链 + 物联网】智慧路灯计费和融资区块链解决方案 | FISCO BCOS应用案例
  • H265视频转换H264视频对应m3u8格式地址播放完整案例