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

JDBC编程详细总结

一、JDBC编程

JDBC编程有标准步骤(八股文)

  • 注册驱动

    • 将sql语句的运行环境加载到JVM

  • 连接数据库

  • 获得执行SQL的对象

  • 执行SQL语句,获得结果

  • 关流

1、 注册驱动

Class.forName("com.mysql.jdbc.Driver");//5.7版本 加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");//5.8版本 加载驱动

2、 连接数据库

  • 通过 DriverManager.getConnection(url,user,password) 获取数据库连接对象

    • URL:jdbc:mysql://localhost:3306/database

      • ?useUnicode=true&characterEncoding=utf8 // 解决数据编码格式乱码

      • &useSSL=false // 解决执行时控制台红色警告

      • &serverTimezone=UTC // mysql8版本需要加时区

    • username:root

    • password:123456

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名字?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC   ", "数据库用户名","数据库密码");
  • URL(Uniform Resource Locator) 统一资源定位符:由协议、IP、端口、SID(程序实例名称)组成

3、 获取发送 SQL 的对象

通过 Connection 对象获得 Statement 对象,用于对数据库进行通用访问。

Statement statement = conn.createStatement();

4、 执行SQL 语句

执行 SQL 语句并接收执行结果。

String sql ="INSERT INTO t_jobs(JOB_ID,JOB_TITLE,MIN_SALARY,MAX_SALARY) VALUES('JAVA_Le','JAVA_Lecturer',4000,10000);";
​
int result = statement.executeUpdate(sql);//执行SQL语句并接收结果
  • 注意:在编写 DML 语句时,一定要注意字符串参数的符号是单引号 '值'

  • DML 语句:增删改时使用executeUpdate(),返回受影响行数(int 类型)。

  • DQL 语句:查询时使用executeQuery(),返回结果数据(ResultSet 结果集)。

5、 处理结果

接受处理操作结果。

if(result > 0 ){System.out.println("Success");
}
  • 受影响行数:逻辑判断、方法返回。

  • 查询结果集:迭代、依次获取。

6、 释放资源

遵循先开后关原则,释放所使用到的资源对象。

statement.close();
conn.close();

7、 案例

准备数据库表,进行CRUD.

create table tb_user(id int(11) primary key auto_increment comment '用户编号',username varchar(10) comment '用户名',password varchar(10) comment '密码',phone varchar(11) comment '手机号',create_time date comment '注册时间',money double(10,2) comment '账户余额',sex int(1) comment '性别 1男2女'
);

需求: 使用JDBC完成对tb_user表插入数据

public class Demo2 {
​public static void main(String[] args) throws ClassNotFoundException, SQLException {// 1 加载驱动Class.forName("com.mysql.jdbc.Driver");
​// 2 获得连接// 通过驱动管理器获得连接String url = "jdbc:mysql://localhost:3306/java2401?useUnicode=true&characterEncoding=utf8&useSSL=false";// 协议://ip:端口/数据库?参数=值&参数=值// http://www.baidu.com:80/s?ie=UTF-8&wd=javaString username = "root";String password = "123456";Connection connection = DriverManager.getConnection(url, username, password);
​// 3 获得执行语句对象// 通过连接对象创建语句对象Statement statement = connection.createStatement( );
​// 4 执行sql获得结果// 通过语句对象执行sql,获得结果// 增删改都是更新,它们执行的结果都是受影响的行数int i = statement.executeUpdate("insert into tb_user values (3,'ww','123','120','2001-01-01',2000.0,2)");if (i > 0) {System.out.println("插入成功!" );}
​// 5 关闭连接statement.close();connection.close();}
​
}

二、完成增删改

1、 插入

参考入门案例

2、 更新

任何的JDBC都是那5个步骤.

public class Demo2_update {
​public static void main(String[] args) throws Exception {
​// 1 加载驱动Class.forName("com.mysql.jdbc.Driver");
​// 2 通过驱动管理对象获得连接对象String url = "jdbc:mysql://localhost:3306/java2311?useSSL=false";String username = "root";String password = "123456";Connection conn = DriverManager.getConnection(url, username, password);
​// 3 通过连接对象创建执行语句对象Statement statement = conn.createStatement( );
​// 4 通过执行语句对象执行sql,获得结果String sql = "update tb_user set username = '小孟', phone = '666666' where id = 3";int num = statement.executeUpdate(sql);
​if (num > 0) {System.out.println("更新成功!" );}// 5 将对象的流关闭statement.close();conn.close();}
}

3、 删除

public class Demo3_delete {
​public static void main(String[] args) {Statement statement = null;Connection conn = null;try {// 1 加载驱动Class.forName("com.mysql.jdbc.Driver");
​// 2 获得连接String url = "jdbc:mysql://localhost:3306/java2311?useSSL=false";String username = "root";String password = "123456";conn = DriverManager.getConnection(url, username, password);
​// 3 获得语句对象statement = conn.createStatement( );
​// 4 执行sqlint num = statement.executeUpdate("delete from tb_user where id = 3");
​if (num > 0) {System.out.println("删除成功" );}}catch (Exception e) {// 如果有异常,要打印出来,因为要根据异常解决问题e.printStackTrace();} finally {try {// 5 关闭连接statement.close( );conn.close( );}catch (SQLException e) {e.printStackTrace();}}}
}

三、查询结果集ResultSet【重要】

查询返回的是一种虚拟表,Java的JDBC中是使用结果集(ResultSet)来封装这个虚拟表,结果集就是一个集合,内部就存储了列名和每行数据,那么学习查询的重点是

  • 从结果集取值

public class Demo4_select {public static void main(String[] args) throws Exception{
​Class.forName("com.mysql.jdbc.Driver");Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/java2311?useSSL=false", "root", "123456");Statement statement = conn.createStatement( );/*** 执行查询方法 executeQuery()* 返回值是 ResultSet 结果集,其中就包含查询返回的所有数据(一张虚拟表)* ResultSet结果集中包含列和行数据,其中有个光标指向表头* next() 方法会向下移动一行,返回boolean,为true即有下一行数据,false该行没数据* 当指向该行后,有方法可以获取该行列值* getXxx()   ps:xxx是各种数据类型* getXxx(String columnLabel) 通过列名取值,如果有别名要使用别名*/String sql = "select birthday,money,username,password,id,sex,age from tb_user";ResultSet rs = statement.executeQuery(sql);while (rs.next()){int id = rs.getInt("id");String username = rs.getString("username");String password = rs.getString("password");String sex = rs.getString("sex");int age = rs.getInt("age");Date birthday = rs.getDate("birthday");double money = rs.getDouble("money");System.out.println(id+"-"+username+"-"+password+"-"+sex+"-"+age+"-"+birthday+"-"+money);}rs.close();statement.close();conn.close();}
}

image-20221121164359945


http://www.mrgr.cn/news/29858.html

相关文章:

  • 「C++系列」异常处理
  • 速盾:凡科建站开cdn了吗?
  • 【从计算机的发展角度理解编程语言】C、CPP、Java、Python,是偶然还是应时代的产物?
  • 硬件开篇——体系架构
  • 408算法题leetcode--第八天
  • [Redis][Redis简介]详细讲解
  • 【无标题】Java_Se 数据变量与运算符
  • Linux C高级 day1
  • 7.7opencv中(基于C++) 翻转图像
  • Linux运维篇-服务器简介
  • 微博计算架构实战
  • Linux进阶 查看系统进程
  • 【漏洞复现】Nacos Derby SQL注入漏洞
  • Java中的语法糖:让编程更简洁的特性
  • 15. 三数之和(左右指针)
  • 【protobuf】ProtoBuf的学习与使用⸺C++
  • Springboot多种请求参数
  • 单细胞BCR的分析Dandelion重注释的安装以及用法----11111
  • java高频面试题(2024最新)
  • MySQL高阶1831-每天的最大交易