Java复习第十二天学习笔记(JDBC),附有道云笔记链接

【有道云笔记】十二 3.28 JDBC

https://note.youdao.com/s/HsgmqRMw

一、JDBC简介

面向接口编程

在JDBC里面Java这个公司只是提供了一套接口Connection、Statement、ResultSet,每个数据库厂商实现了这套接口,例如MySql公司实现了:MySql驱动程序里面实现了这套接口,Java程序员只要调用实现了这些方法就可以实现对 MySql数据库的增删改查。

ConnectIon connection= 获得连接;

二、JDBC开发步骤

1、加载驱动Class.forName("");

2、获得连接对象Connection

3、写sql语句

4、创建Statement(一艘船)

5、执行sql语句

(1) 更新类(更改了表里面数据):delete/update/insert executeUpdate()

返回值:int,表示你影响的行数

(2)查询(没有改变表里面数据): select executeQuery()

返回值:结果集ResultSet

6、关闭连接

//1、加载驱动Class.forName(""); Class.forName("com.mysql.cj.jdbc.Driver"); //2、获得连接对象Connection Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/java230701?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2b8", "root", "1234");

@Test public void test1() { try { //1、加载驱动Class.forName(""); Class.forName("com.mysql.cj.jdbc.Driver"); //2、获得连接对象Connection Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/java230701?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2b8", "root", "1234"); //3、写sql语句 String sql = "SELECT id,name,age,gender FROM student"; //4、创建Statement(一艘船) Statement statement = connection.createStatement(); //5、执行sql语句 // (1) 更新类(更改了表里面数据):delete/update/insert executeUpdate() // 返回值:int,表示你影响的行数 // (2)查询(没有改变表里面数据): select executeQuery() // 返回值:结果集ResultSet ResultSet resultSet = statement.executeQuery(sql); List<Student> list = new ArrayList<>(); while (resultSet.next()) {//判断下一个有没有,如果返回true而且指向下一个,没有返回false //每遍历一行,就封装一个学生对象 int id = resultSet.getInt("id"); String name = resultSet.getString("name"); int age = resultSet.getInt("age"); String gender = resultSet.getString("gender"); Student student = new Student(id, name, age, gender); list.add(student); } for (Student student : list) { System.out.println(student); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException throwables) { throwables.printStackTrace(); } finally { //6、关闭连接 } } @Test public void test2() { Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { Class.forName("com.mysql.cj.jdbc.Driver"); connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/java230701?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2b8", "root", "1234"); String sql = "SELECT id,name,age,gender FROM student"; statement = connection.createStatement(); resultSet = statement.executeQuery(sql); List<Student> list = new ArrayList<>(); while (resultSet.next()) {//判断下一个有没有,如果返回true而且指向下一个,没有返回false int id = resultSet.getInt("id"); String name = resultSet.getString("name"); int age = resultSet.getInt("age"); String gender = resultSet.getString("gender"); Student student = new Student(id, name, age, gender); list.add(student); } for (Student student : list) { System.out.println(student); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException throwables) { throwables.printStackTrace(); } finally { if (resultSet != null) { try { resultSet.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (statement != null) { try { statement.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } } @Test public void testPreparedStatement() { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = JDBCUtil.getConnection(); String sql = "SELECT id,name,age,gender FROM student"; //预编译 preparedStatement = connection.prepareStatement(sql); resultSet = preparedStatement.executeQuery(); List<Student> list = new ArrayList<>(); while (resultSet.next()) {//判断下一个有没有,如果返回true而且指向下一个,没有返回false int id = resultSet.getInt("id"); String name = resultSet.getString("name"); int age = resultSet.getInt("age"); String gender = resultSet.getString("gender"); Student student = new Student(id, name, age, gender); list.add(student); } for (Student student : list) { System.out.println(student); } } catch (SQLException throwables) { throwables.printStackTrace(); } finally { JDBCUtil.close(connection, preparedStatement, resultSet); } } @Test public void testInsert() { Connection connection = null; PreparedStatement preparedStatement = null; try { connection = JDBCUtil.getConnection(); //? 占位符 String sql = "insert into student(name,age,gender) values(?,?,?)"; preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, "张三"); preparedStatement.setInt(2, 23); preparedStatement.setString(3, "女"); System.out.println(preparedStatement); int count = preparedStatement.executeUpdate(); System.out.println("count: " + count); } catch (SQLException throwables) { throwables.printStackTrace(); } finally { JDBCUtil.close(connection, preparedStatement, null); } } @Test public void testDelete() { Connection connection = null; PreparedStatement preparedStatement = null; try { connection = JDBCUtil.getConnection(); String sql = "delete from student where id=?"; preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1, 10); System.out.println(preparedStatement); int count = preparedStatement.executeUpdate(); System.out.println("count: " + count); } catch (SQLException throwables) { throwables.printStackTrace(); } finally { JDBCUtil.close(connection, preparedStatement, null); } } @Test public void testUpdate() { Connection connection = null; PreparedStatement preparedStatement = null; try { connection = JDBCUtil.getConnection(); String sql = "update student set name=?,age=?,gender=? where id=?"; preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, "小张"); preparedStatement.setInt(2, 23); preparedStatement.setString(3, "男"); preparedStatement.setInt(4, 9); System.out.println(preparedStatement); int count = preparedStatement.executeUpdate(); System.out.println("count: " + count); } catch (SQLException throwables) { throwables.printStackTrace(); } } @Test public void testLike() { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = JDBCUtil.getConnection(); String sql = "select id,name,age,gender from student where name like ?"; preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, "%张%"); System.out.println(preparedStatement); resultSet = preparedStatement.executeQuery(); List<Student> list = new ArrayList<>(); while (resultSet.next()) { int id = resultSet.getInt("id"); String name = resultSet.getString("name"); int age = resultSet.getInt("age"); String gender = resultSet.getString("gender"); Student student = new Student(id, name, age, gender); list.add(student); } for (Student student : list) { System.out.println(student); } } catch (SQLException throwables) { throwables.printStackTrace(); } } @Test public void test122() { Connection connection = null; PreparedStatement preparedStatement = null; String sql1 = "UPDATE account SET money=money-1000 WHERE name='张三'"; String sql2 = "UPDATE account SET money=money+1000 WHERE name='李四'"; try { connection = JDBCUtil.getConnection(); // 为false,表示禁用自动提交(默认情况是true) connection.setAutoCommit(false); preparedStatement = connection.prepareStatement(sql1); System.out.println(preparedStatement); preparedStatement.executeUpdate(); // ArithmeticException: / by zero int i = 3 / 0; preparedStatement = connection.prepareStatement(sql2); System.out.println(preparedStatement); preparedStatement.executeUpdate(); // setAutoCommit(false)改成false之后,不会提交数据库,只有调用connection.commit()才提交 connection.commit(); } catch (Exception e) { e.printStackTrace(); try { connection.rollback(); } catch (SQLException throwables) { throwables.printStackTrace(); } } finally { JDBCUtil.close(connection, preparedStatement, null); } }

三、JDBC接口核心的API

|- DriverManager类: 驱动管理器类,用于管理所有注册的驱动程序

|-registerDriver(driver) : 注册驱动类对象

|-Connection getConnection(url,user,password); 获取连接对象

|- Connection接口: 表示java程序和数据库的连接对象。

|- Statement createStatement() : 创建Statement对象

|- PreparedStatement prepareStatement(String sql) 创建PreparedStatement对象

|- CallableStatement prepareCall(String sql) 创建CallableStatement对象(调用写好的存储过程)

|- Statement接口: 用于执行静态的sql语句

|- int executeUpdate(String sql) : 执行静态的更新sql语句

|- ResultSet executeQuery(String sql) :执行的静态的查询sql语句

|-PreparedStatement接口:用于执行预编译sql语句

|- int executeUpdate() : 执行预编译的更新sql语句

|-ResultSet executeQuery() : 执行预编译的查询sql语句

|- ResultSet接口:用于封装查询出来的数据

|- boolean next() : 将光标移动到下一行

|-getXX() : 获取列的值

四、PreparedStatement(预编译)和Statement区别

1、语法不同:

PreparedStatement可以使用预编译的sql,只需要发送一次sql语句,后面只要发送参数即可,公用一个sql语句。

Statement只能使用静态的sql。

delete from student where id=1;

2、效率不同:PreparedStatement使用了sql缓冲区,效率要比Statement高。

3、安全性不同:PreparedStatement可以有效的防止sql注入,而Statement不能防止sql注入。

CREATE TABLE users( id INT PRIMARY KEY AUTO_INCREMENT, `name` VARCHAR(10), `password` VARCHAR(10) ); INSERT INTO users(`name`, `password`) VALUES('lisi',123); SELECT * FROM users WHERE 1=1; -- 1=1 true SELECT * FROM users WHERE `name`='lisi' AND `password`='123'; -- zhangsan' OR 1=1 -- y SELECT * FROM users WHERE `name`='zhangsan' OR 1=1 -- y' AND `password`='343';

相关推荐
路在脚下@12 分钟前
spring boot的配置文件属性注入到类的静态属性
java·spring boot·sql
森屿Serien15 分钟前
Spring Boot常用注解
java·spring boot·后端
量子-Alex40 分钟前
【多模态聚类】用于无标记视频自监督学习的多模态聚类网络
学习·音视频·聚类
吉大一菜鸡44 分钟前
FPGA学习(基于小梅哥Xilinx FPGA)学习笔记
笔记·学习·fpga开发
苹果醋31 小时前
React源码02 - 基础知识 React API 一览
java·运维·spring boot·mysql·nginx
Hello.Reader2 小时前
深入解析 Apache APISIX
java·apache
菠萝蚊鸭2 小时前
Dhatim FastExcel 读写 Excel 文件
java·excel·fastexcel
旭东怪2 小时前
EasyPoi 使用$fe:模板语法生成Word动态行
java·前端·word
007php0072 小时前
Go语言zero项目部署后启动失败问题分析与解决
java·服务器·网络·python·golang·php·ai编程
∝请叫*我简单先生2 小时前
java如何使用poi-tl在word模板里渲染多张图片
java·后端·poi-tl