软件设计之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或端口写错了,会报如下异常

  • 12
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值