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

Java操作数据库 —— JDBC ① 基础篇

我走我的路,有人拦也走,没人陪也走

                                                —— 24.6.7

JDBC

JDBC就是使用Java语言操作关系型数据库的一套API

一、JDBC简介

JDBC 概念

        JDBC 就是使用Java语言操作关系型数据库的一套API

        全称:(Java DataBase Connectivity)意为Java 数据库连接

JDBC 本质:

        ① 官方(sun公司)定义的一套操作所有关系型数据库的规则,即接口

        ② 各个数据库厂商去实现这套接口,提供数据库驱动jar包

        ③ 我们可以使用这套接口(JDBC)编程,真正执行的代码是驱动jar包中的实现类

JDBC 好处:

        ① 各数据库厂商使用相同的接口,Java代码不需要针对不同数据库分别开发

        ② 可随时替换底层数据库,访问数据库的Java代码基本不变

二、JDBC快速入门

步骤

package JavaJDBCBase;import java.sql.*;public class Demo1JDBCQuick {public static void main(String[] args) throws ClassNotFoundException, SQLException {// 1. 注册驱动Class.forName("com.mysql.cj.jdbc.Driver");// 2.获取数据库连接String url = "jdbc:mysql://localhost:3306/JDBC";// 用户名String username = "root";// 密码String password = "954926928lcl";// 获取链接对象Connection conn = DriverManager.getConnection(url,username,password);// 3.获取执行sql的对象,statement(把sql语句发送给MySQL)Statement stmt = conn.createStatement();// 4.编写sql语句并执行,以及接收返回的结果集String sql = "select emp_id,emp_name,emp_salary,emp_age from t_tmp";ResultSet result = stmt.executeQuery(sql);// 5.处理结果,遍历result结果集 next方法,判断有没有下一行while (result.next()) {int empId = result.getInt("emp_id");String empName = result.getString("emp_name");double empSalary = result.getDouble("emp_salary");int empAge = result.getInt("emp_age");System.out.println(empId+"\t"+empName+"\t"+empSalary+"\t"+empAge);}// 6.释放资源 先开启后关闭原则result.close();stmt.close();conn.close();}
}

三、JDBC 核心API 详解 

1.注册驱动

Class.forName("com.mysql.cj.jdbc.Driver");

在 Java 中,当使用 JDBC(Java Database Connectivity)连接数据库时,需要加载数据库特定的驱动程序,以便与数据库进行通信。加载驱动程序的目的是为了注册驱动程序使得 JDBC API能够识别并与特定的数据库进行交互。

        // 1. 注册驱动
//        Class.forName("com.mysql.cj.jdbc.Driver");DriverManager.registerDriver(new Driver());

从JDK6开始,不再需要显式地调用 class.forName()来加载JDBC 驱动程序,只要在类路径中集成了对应的jar文件,会自动在初始化时注册驱动程序。

2.Connection

        Connection接口是JDBC API的重要接口,用于建立与数据库的通信通道。换而言之,Connection对象不为空则代表一次数据库连接。
        在建立连接时,需要指定数据库URL、用户名、密码参数。
                URL:jdbc:mysql://localhost:3306/atguigu"

                        jdbc:mysql://IP地址:端口号/数据库名称 ? 参数键值对1 & 参数键值对2

        Connection 接口还负责管理事务,Connection 接口提供了 commitrollback 方法,用于提交事务和回滚事务。
        可以创建 statement 对象,用于执行 SQL语句并与数据库进行交互。
        在使用JDBC技术时,必须要先获取Connection对象,在使用完毕后,要释放资源,避免资源占用浪费及泄漏。

3.Statement(了解)

        Statement 接口用于执行 SQL语句并与数据库进行交互。它是 JDBC API 中的一个重要接口。通过Statement 对象,可以向数据库发送 SQL语句并获取执行结果。
        结果可以是一个或多个结果。
                增删改:受影响行数单个结果。
                查询:单行单列、多行多列、单行多列等结果。
        但是 Statement 接口在执行SQL语句时,会产生SQL注入攻击问题:
        当使用 statement 执行动态构建的 SQL查询时,往往需要将查询条件与SQL语句拼接在一起,直接将参数和SQL语句一并生成,让SQL的查询条件始终为true得到结果。

4.PreparedStatement

        Preparedstatement是 Statement 接口的子接口,用于执行 预编译的 SQL查询,作用如下。

        预编译SQL语句:在创建Preparedstatement时,就会预编译SQL语句,也就是SQL语句已经固定 
        防止SQL注入: Preparedstatement 支持参数化查询,将数据作为参数传递到SQL语句中,采用?占位符的方式,将传入的参数用一对单引号包裹起来",无论传递什么都作为值。有效防止传入关键字或值导致SQL注入问题。
        性能提升:Preparedstatement是预编译SQL语句,同一SQL语句多次执行的情况下,可以复用,不必每次重新编译和解析。

import java.sql.*;
import java.util.Scanner;public class Demo2PreparedStatement {public static void main(String[] args) throws Exception {// 1.注册驱动// 2.获取链接对象String url = "jdbc:mysql://localhost:3306/JDBC";// 用户名String username = "root";// 密码String password = "954926928lcl";Connection conn = DriverManager.getConnection(url,username,password);// 3.获取执行sql语句对象PreparedStatement preparedStatement = conn.prepareStatement("select emp_id,emp_name,emp_salary,emp_age from t_tmp where emp_id=?");System.out.println("请输入员工编号:");Scanner sc = new Scanner(System.in);String name = sc.nextLine();// 4.为?占位符赋值,并执行sql语句,并执行,接受返回的结果preparedStatement.setString(1,name);ResultSet resultSet = preparedStatement.executeQuery();// 5.处理结果,遍历esultSetwhile(resultSet.next()){int emp_id = resultSet.getInt("emp_id");String emp_name = resultSet.getString("emp_name");int emp_age = resultSet.getInt("emp_age");double emp_salary = resultSet.getDouble("emp_salary");System.out.println(emp_id+"\t"+emp_name+"\t"+emp_age+"\t"+emp_salary);}// 6.释放资源resultSet.close();preparedStatement.close();conn.close();}
}

package JavaJDBCBase;import java.sql.*;
import java.util.Scanner;public class Demo2PreparedStatement {public static void main(String[] args) throws Exception {// 1.注册驱动// 2.获取链接对象String url = "jdbc:mysql://localhost:3306/JDBC";// 用户名String username = "root";// 密码String password = "954926928lcl";Connection conn = DriverManager.getConnection(url,username,password);// 3.获取执行sql语句对象PreparedStatement preparedStatement = conn.prepareStatement("select emp_id,emp_name,emp_salary,emp_age from t_tmp where emp_name=? || emp_salary=?");System.out.println("请输入员工姓名:");Scanner sc = new Scanner(System.in);String name = sc.nextLine();System.out.println("请输入员工工资");double salary = sc.nextDouble();// 4.为?占位符赋值,并执行sql语句,并执行,接受返回的结果 int类型:参数的下标,从0开始,要替换的值为多少preparedStatement.setString(1,name);preparedStatement.setDouble(2,salary);ResultSet resultSet = preparedStatement.executeQuery();// 5.处理结果,遍历resultSetwhile(resultSet.next()){int emp_id = resultSet.getInt("emp_id");String emp_name = resultSet.getString("emp_name");int emp_age = resultSet.getInt("emp_age");double emp_salary = resultSet.getDouble("emp_salary");System.out.println(emp_id+"\t"+emp_name+"\t"+emp_age+"\t"+emp_salary);String goal = resultSet.getString("emp_id");System.out.println(emp_name+"id为:"+goal);}// 6.释放资源resultSet.close();preparedStatement.close();conn.close();}
}

5.ResultSet

        ResultSet 是JDBC API中的一个接口,用于表示从数据库中 执行査询语句所返回的结果集。它提供了一种于遍历和访问查询结果的方式。
        遍历结果:Resultset可以使用 next()方法将游标移动到结果集的下一行,逐行遍历数据库查询的结果,返回值为boolean类型,true代表有下一行结果,false则代表没有。

        获取单列结果:可以通过get类型()的方法获取单列的数据,该方法为重载方法,支持索引和列名进行获取。

    String goal = resultSet.getString("emp_name");System.out.println(goal);
package JavaJDBCBase;import java.sql.*;
import java.util.Scanner;public class Demo2PreparedStatement {public static void main(String[] args) throws Exception {// 1.注册驱动// 2.获取链接对象String url = "jdbc:mysql://localhost:3306/JDBC";// 用户名String username = "root";// 密码String password = "954926928lcl";Connection conn = DriverManager.getConnection(url,username,password);// 3.获取执行sql语句对象PreparedStatement preparedStatement = conn.prepareStatement("select emp_id,emp_name,emp_salary,emp_age from t_tmp where emp_id=?");System.out.println("请输入员工编号:");Scanner sc = new Scanner(System.in);String name = sc.nextLine();// 4.为?占位符赋值,并执行sql语句,并执行,接受返回的结果preparedStatement.setString(1,name);ResultSet resultSet = preparedStatement.executeQuery();// 5.处理结果,遍历esultSetwhile(resultSet.next()){int emp_id = resultSet.getInt("emp_id");String emp_name = resultSet.getString("emp_name");int emp_age = resultSet.getInt("emp_age");double emp_salary = resultSet.getDouble("emp_salary");System.out.println(emp_id+"\t"+emp_name+"\t"+emp_age+"\t"+emp_salary);String goal = resultSet.getString("emp_name");System.out.println(goal);}// 6.释放资源resultSet.close();preparedStatement.close();conn.close();}
}

四、基于Preparedstatement实现CRUD

1.查询单行单列

    // 单行单列查询@Testpublic void testQuerySingleRowAndCol() throws SQLException {// 1.注册驱动// 2.获取连接String url = "jdbc:mysql://localhost:3306/JDBC";// 用户名String username = "root";// 密码String password = "954926928lcl";Connection connection = DriverManager.getConnection(url, username, password);// 3.预编译SQL语句得到PreparedStatement对象PreparedStatement preparedStatement = connection.prepareStatement("select count(*) as count from t_tmp");// 4.执行语句 获取结果ResultSet resultSet = preparedStatement.executeQuery();// 5.处理结果,进行遍历,如果明确只有一个结果,那么resultSet至少要做一次next的判断,才能拿到我们要的列的结果while (resultSet.next()) {// 用下标获取int anInt = resultSet.getInt(1);System.out.println(anInt);}// 6.释放资源resultSet.close();preparedStatement.close();connection.close();}

2.查询单行多列

    // 单行多列查询@Testpublic void testQuerySingleRowAndCol2() throws SQLException {// 1.注册驱动// 2.获取链接Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/JDBC", "root", "954926928lcl");// 3.预编译SQL语句获得PreparedStatement对象PreparedStatement preparedStatement = connection.prepareStatement("select emp_id,emp_name,emp_salary,emp_age from t_tmp where emp_id = ?");// 4.为占位符赋值,然后执行,并接受结果preparedStatement.setInt(1,5);ResultSet resultSet = preparedStatement.executeQuery();// 5.处理结果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();}

3.查询多行多列

    // 多行多列查询@Testpublic void testQueryMoreRow() throws SQLException {String url = "jdbc:mysql://localhost:3306/JDBC";// 用户名String username = "root";// 密码String password = "954926928lcl";Connection conn = DriverManager.getConnection(url,username,password);PreparedStatement preparedStatement = conn.prepareStatement("select emp_id,emp_name,emp_salary,emp_age from t_tmp where emp_age > ?");preparedStatement.setInt(1,25);ResultSet resultSet = preparedStatement.executeQuery();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);}resultSet.close();preparedStatement.close();conn.close();}

4.新增

    // 新增@Testpublic void testInsert() throws SQLException {String url = "jdbc:mysql://localhost:3306/JDBC";// 用户名String username = "root";// 密码String password = "954926928lcl";// 获取链接对象Connection conn = DriverManager.getConnection(url,username,password);PreparedStatement preparedStatement = conn.prepareStatement("insert into t_tmp(emp_name,emp_salary,emp_age) values(?,?,?)");preparedStatement.setString(1,"rose");preparedStatement.setDouble(2,345.67);preparedStatement.setInt(3,36);int result = preparedStatement.executeUpdate();// 根据受影响行数做判断,得到成功或失败if (result>0){System.out.println("成功!");}else{System.out.println("失败!");}preparedStatement.close();conn.close();}

5.修改

    // 修改@Testpublic void testUpdate() throws SQLException {String url = "jdbc:mysql://localhost:3306/JDBC";// 用户名String username = "root";// 密码String password = "954926928lcl";// 获取链接对象Connection conn = DriverManager.getConnection(url,username,password);PreparedStatement preparedStatement = conn.prepareStatement("update t_tmp set emp_salary = ? where emp_id=?");preparedStatement.setDouble(1,888.88);preparedStatement.setInt(2,6);int result = preparedStatement.executeUpdate();if (result>0){System.out.println("成功");}else{System.out.println("失败");}preparedStatement.close();conn.close();}

6.删除

    // 删除@Testpublic void testDelete() throws SQLException {String url = "jdbc:mysql://localhost:3306/JDBC";// 用户名String username = "root";// 密码String password = "954926928lcl";// 获取链接对象Connection conn = DriverManager.getConnection(url,username,password);// 手写SQL语句PreparedStatement preparedStatement = conn.prepareStatement("delete from t_tmp where emp_id=?");preparedStatement.setInt(1,5);int result = preparedStatement.executeUpdate();if (result>0){System.out.println("成功");}else{System.out.println("失败");}preparedStatement.close();conn.close();}

7.总结

package JavaJDBCBase;// 在类中写入@Test,自动导入org.junit.Test,便不用重复写main函数
import org.junit.Test;import java.sql.*;public class Demo3JDBCOperation {// 单行单列查询@Testpublic void testQuerySingleRowAndCol() throws SQLException {// 1.注册驱动// 2.获取连接String url = "jdbc:mysql://localhost:3306/JDBC";// 用户名String username = "root";// 密码String password = "954926928lcl";Connection connection = DriverManager.getConnection(url, username, password);// 3.预编译SQL语句得到PreparedStatement对象PreparedStatement preparedStatement = connection.prepareStatement("select count(*) as count from t_tmp");// 4.执行语句 获取结果ResultSet resultSet = preparedStatement.executeQuery();// 5.处理结果,进行遍历,如果明确只有一个结果,那么resultSet至少要做一次next的判断,才能拿到我们要的列的结果while (resultSet.next()) {// 用下标获取int anInt = resultSet.getInt(1);System.out.println(anInt);}// 6.释放资源resultSet.close();preparedStatement.close();connection.close();}// 单行多列查询@Testpublic void testQuerySingleRowAndCol2() throws SQLException {// 1.注册驱动// 2.获取链接Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/JDBC", "root", "954926928lcl");// 3.预编译SQL语句获得PreparedStatement对象PreparedStatement preparedStatement = connection.prepareStatement("select emp_id,emp_name,emp_salary,emp_age from t_tmp where emp_id = ?");// 4.为占位符赋值,然后执行,并接受结果preparedStatement.setInt(1,5);ResultSet resultSet = preparedStatement.executeQuery();// 5.处理结果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();}// 多行多列查询@Testpublic void testQueryMoreRow() throws SQLException {String url = "jdbc:mysql://localhost:3306/JDBC";// 用户名String username = "root";// 密码String password = "954926928lcl";Connection conn = DriverManager.getConnection(url,username,password);PreparedStatement preparedStatement = conn.prepareStatement("select emp_id,emp_name,emp_salary,emp_age from t_tmp where emp_age > ?");preparedStatement.setInt(1,25);ResultSet resultSet = preparedStatement.executeQuery();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);}resultSet.close();preparedStatement.close();conn.close();}// 新增@Testpublic void testInsert() throws SQLException {String url = "jdbc:mysql://localhost:3306/JDBC";// 用户名String username = "root";// 密码String password = "954926928lcl";// 获取链接对象Connection conn = DriverManager.getConnection(url,username,password);PreparedStatement preparedStatement = conn.prepareStatement("insert into t_tmp(emp_name,emp_salary,emp_age) values(?,?,?)");preparedStatement.setString(1,"rose");preparedStatement.setDouble(2,345.67);preparedStatement.setInt(3,36);int result = preparedStatement.executeUpdate();// 根据受影响行数做判断,得到成功或失败if (result>0){System.out.println("成功!");}else{System.out.println("失败!");}preparedStatement.close();conn.close();}// 修改@Testpublic void testUpdate() throws SQLException {String url = "jdbc:mysql://localhost:3306/JDBC";// 用户名String username = "root";// 密码String password = "954926928lcl";// 获取链接对象Connection conn = DriverManager.getConnection(url,username,password);PreparedStatement preparedStatement = conn.prepareStatement("update t_tmp set emp_salary = ? where emp_id=?");preparedStatement.setDouble(1,888.88);preparedStatement.setInt(2,6);int result = preparedStatement.executeUpdate();if (result>0){System.out.println("成功");}else{System.out.println("失败");}preparedStatement.close();conn.close();}// 删除@Testpublic void testDelete() throws SQLException {String url = "jdbc:mysql://localhost:3306/JDBC";// 用户名String username = "root";// 密码String password = "954926928lcl";// 获取链接对象Connection conn = DriverManager.getConnection(url,username,password);// 手写SQL语句PreparedStatement preparedStatement = conn.prepareStatement("delete from t_tmp where emp_id=?");preparedStatement.setInt(1,5);int result = preparedStatement.executeUpdate();if (result>0){System.out.println("成功");}else{System.out.println("失败");}preparedStatement.close();conn.close();}
}

五、常见问题

1.资源的管理

2.SQL语句问题

3.SQL语句未设置参数问题

4.用户名或密码错误问题

5.通信异常

http://www.lryc.cn/news/369514.html

相关文章:

  • webpack和vite区别
  • FL Studio21永久免费破解中文版下载,让我这个音乐制作爱好者如获至宝!
  • vue3 监听器,组合式API的watch用法
  • 苹果WWDC开幕发布AI大模型,股价却跌近2%
  • C++ 11 【可变参数模板】【lambda】
  • c 宏应用举例
  • 微信公众号(公众平台) 和 微信开放平台的scope的差异
  • 基于pytorch实现的DenseUnet医学图像分割(腹部多脏器)
  • 富格林:正规策划实现安全做单
  • 02. 异常捕捉和处理
  • Oracle和mysql中插入时间字段
  • 注册小程序
  • 【YOLOv8改进[CONV]】使用MSBlock二次创新C2f模块实现轻量化 + 含全部代码和详细修改方式 + 手撕结构图 + 轻量化 + 涨点
  • three.js使用环境贴图或者加载hdr图
  • GPT-4o多模态大模型的架构设计
  • Facebook:社交世界的引领者
  • qt 加载字体 c++
  • Linux ldd和ldconfig
  • Python 学习flask创建项目
  • .NET集成DeveloperSharp实现图片的裁剪、缩放、与加水印
  • 阿里发布最强开源大模型通义千问Qwen2,国产最好用的LLM
  • 探索风电机组:关键软件工具全解析
  • HOW - CSS 常见效果实现
  • EI/CPCI/Scopus会议论文是啥?
  • 【递归、搜索与回溯】穷举vs暴搜vs深搜vs回溯vs剪枝
  • celery-redbeat方案(动态定时任务、异步任务)
  • js解析成语法树以及还原
  • 基于python可伸缩JSON格式列表实现
  • h5相机功能
  • IDEA | 安装通义灵码插件,开启智能编码旅程