JDBC的增删改查

1 什么是JDBC

概念: Java 数据库连接,( Java Database Connectivity ,简称 JDBC )是 Java 语言 中用来规范客户端程序
如何来访问数据库的 应用程序接口 ,提供了诸如查询和更新数据库中数据的方法。 JDBC 也是 Sun
Microsystems 的商标。我们通常说的 JDBC 是面向关系型数据库的。
各数据库厂商根据 JDBC 的规范,实现自身数据库操作的功能代码,然后以 jar 包(数据库厂商提供的驱动
包)的形式提供给开发人员使用,开发人员使用反射的机制创建这些具体实现类,按照 JDBC 的规范来完
成数据库的操作。

接口和JDBC规范的理解:

2 创建数据库

创建学生信息表

#设置数据的视图---使用数据库
use mydb;
#判断表存在就删除表
drop table if exists student;
#创建表
create table student
(
stuId int primary key auto_increment,
stuName varchar(20),
stuSex varchar(2),
stuAge int,
stuAddr varchar(50)
);
#插入测试数据
insert into student(stuName,stuSex,stuAge,stuAddr) values('张三','男',20,'河南');
insert into student(stuName,stuSex,stuAge,stuAddr) values('小美','女',18,'山东');
insert into student(stuName,stuSex,stuAge,stuAddr) values('Rose','女',19,'美国');
insert into student(stuName,stuSex,stuAge,stuAddr) values('Jack','男',21,'英国');
#查询数据表
select * from student;

3 JDBC的增删改查

3.1 先在IDEA中创建实体类:类的名字对应数据库表的名字、类的属

性对应表的字段

public class Student {
//属性
private int stuId;
private String stuName;
private String stuSex;
private int stuAge;
private String stuAddr;
//IDEA自动构造代码快捷键: alt + insert

3.2 JDBC的查询操作

junit 的用法补充 :junit 可以使方法脱离 main 方法直接执行,方便进行程序测试。
package com.hp.test2;
import org.junit.Test;
public class StudentTest {
/*
junit用法:1.方法要定义为无参无返回值的。且测试类的名字不能是Test
2.在方法上使用 @Test 这个注解
3.光标放在后面,然后使用 alt + 回车 进行自动导包,选择---Add 'JUnit4' to
classpath
4.这个方法就不需要依赖main方法就可以直接执行
*/
@Test
public void testSelectAll(){
System.out.println("testSelectAll执行...");
}
}
JDBC 的全查操作
public class StudentTest { 
  /**
  * JDBC连接数据库,需要配置四大参数,同时需要导入数据库对应的驱动包
  */
private String driver="com.mysql.cj.jdbc.Driver";
private String url="jdbc:mysql://127.0.0.1:3306/mydb?
useSSL=false&serverTimezone=UTC";
private String username="root";
private String password="123";
@Test
public void testSelectAll() throws ClassNotFoundException, SQLException {
//JDBC操作数据库的步骤
//1.首先在项目根目录创建lib文件夹,放入jdbc驱动程序,然后Add As Library
//2.加载数据库驱动
Class.forName(driver);
//3.使用驱动管理器来获得连接---获得一个数据库连接对象Connection
Connection con=DriverManager.getConnection(url, username, password); //
生成方法调用返回值的快捷键:ctrl + alt + v
//4.使用Connection创建PreparedStatement预处理对象---PreparedStatement对象可以
执行带 ? 的sql语句
String sql="select * from student";
PreparedStatement pstm = con.prepareStatement(sql);
//5.使用PreparedStatement对象执行SQL语句,获得ResultSet结果集对象
ResultSet rs = pstm.executeQuery();
//6.操作判断--增删改返回的是影响的行数(返回值是int),只有查询获得结果集(返回值
ResultSet)
//让结果集的游标不断的往下移动,直到没有数据的时候结束循环
List<Student> studentList=new ArrayList<>(); //定义集合(大的容器),用来装
Student对象(小容器)
while(rs.next()){
//根据字段名称获取表中的数据
int stuId=rs.getInt("stuId");
String stuName=rs.getString("stuName");
String stuSex=rs.getString("stuSex");
int stuAge=rs.getInt("stuAge");
String stuAddr=rs.getString("stuAddr");
//把以上数据封装到Student对象中
Student student=new Student(); //一行数据就封装成了一个Student对象
student.setStuId(stuId);
student.setStuName(stuName);
student.setStuSex(stuSex);
student.setStuAge(stuAge);
student.setStuAddr(stuAddr);
//把当前行封装后的Student对象装载到 List集合中
studentList.add(student);
}
System.out.println(studentList);
//7.回收资源,先关闭rs结果集对象 再pstm预处理对象 最后con连接对象
if(rs!=null){
rs.close();
}
if(pstm!=null){
pstm.close();
}
if(con!=null){
con.close();
}
}
}

2JDBC的添加操作

/**
* 添加操作
*/
@Test
public void testAdd() throws Exception {
//1.导入驱动包
//2.通过反射加载驱动程序
Class.forName(driver);
//3.通过驱动管理器获得数据库的连接对象
Connection con = DriverManager.getConnection(url, username, password);
//4.通过连接对象,获取SQ预处理对象
String sql="insert into student(stuName,stuSex,stuAge,stuAddr)
values(?,?,?,?)";
PreparedStatement pstm = con.prepareStatement(sql);
//实际开发是前端页面传递过来的数据,此处我们直接模拟一组数据
Student student=new Student();
student.setStuName("张三");
student.setStuSex("男");
student.setStuAge(18);
student.setStuAddr("南阳");
//5.1预处理对象的sql语句有 ? 所以需要进行传参
pstm.setObject(1,student.getStuName());
pstm.setObject(2,student.getStuSex());
pstm.setObject(3,student.getStuAge());
pstm.setObject(4,student.getStuAddr());
//5.2执行更新(增删改都叫做数据库的更新,更新返回的是影响的行数)
int n = pstm.executeUpdate();
//6判断影响的行数 n > 0 表示插入成功,否则插入失败
if(n>0){
System.out.println("插入数据成功");
}else{
System.out.println("插入数据失败");
}
//7释放资源
if(pstm!=null){
pstm.close();
}
if(con!=null){
con.close();
}
}

JDBC的删除操作

/**
* 删除操作
*/
@Test
public void testDel() throws Exception {
//1.导入驱动程序包
//2.通过反射加载驱动程序
Class.forName(driver);
//3.通过驱动管理器获得数据库的连接对象
Connection con = DriverManager.getConnection(url, username, password);
//4.通过数据库连接对象获取sql预处理对象
String sql="delete from student where stuId=?";
PreparedStatement pstm = con.prepareStatement(sql);
//5.1预处理对象的sql语句有 ? ,所以需要传参
int stuId=3; //实际开发是从前端页面获取要删除的id
pstm.setObject(1,stuId);
//5.2执行更新操作(增删改都是更新操作,返回的结果是影响的行数)
int n=pstm.executeUpdate();
//6判断影响的行数 n>0 表示删除成功,否则删除失败
if(n>0){
System.out.println("删除成功");
} else {
System.out.println("删除失败");
}
//7释放资源
if(pstm!=null){
pstm.close();
}
if(con!=null){
con.close();
}
}

JDBC的修改操作

/**
* 修改操作
* @throws Exception
*/
@Test
public void testUpdate() throws Exception {
//===========修改的业务逻辑===================
//第一步:根据id先查询原始数据
Student student = selectById(4);
System.out.println("修改前:"+student);
//第二步:根据需要修改原始数据的字段值 (后期学习是用前端html页面修改数据,然后传输过
来新的数据)
Scanner sc=new Scanner(System.in);
System.out.println("请修改名字:");
String newName=sc.next();
student.setStuName(newName);
System.out.println("请修改性别:");
String newSex=sc.next();
student.setStuSex(newSex);
System.out.println("请修改年龄:");
模糊查询一般是通过一个输入框输入关键词,然后点击搜索进行检索,执行的是数据的模糊查询;
语句示例:select * from student where stuName like '%关键词%';
int newAge=sc.nextInt();
student.setStuAge(newAge);
System.out.println("请修改地址:");
String newAddr=sc.next();
student.setStuAddr(newAddr);
System.out.println("修改后:"+student);
//第三步:修改字段值后把最新的数据执行数据库JDBC的修改操作
//1.导入jar包
//2.使用反射加载驱动程序
Class.forName(driver);
//3.使用驱动管理器获得数据库的连接
Connection con = DriverManager.getConnection(url, user, password);
//4.使用连接对象获取SQL的预处理对象
String sql="update student set stuName=?,stuSex=?,stuAge=?,stuAddr=?
where stuId=?";
PreparedStatement pstm = con.prepareStatement(sql);
//5.传参并执行SQL
pstm.setObject(1,student.getStuName());
pstm.setObject(2,student.getStuSex());
pstm.setObject(3,student.getStuAge());
pstm.setObject(4,student.getStuAddr());
pstm.setObject(5,student.getStuId());
int n = pstm.executeUpdate();
//6.判断执行结果
if(n>0){
System.out.println("修改成功");
}else{
System.out.println("修改失败");
}
//7.释放资源
if(pstm!=null){
pstm.close();
}
if(con!=null){
con.close();
}
}

JDBC的模糊查询

5.1 模糊查询的基础版代码如下:

因为sql语句是 select * from student where stuName like ?; 所以传参的时候需要对关键词进行前后 % 的拼接: String keyword="a"; //后期是通过页面获取用户输入的关键词 pstm.setObject(1,"%"+keyword+"%"); //对关键词进行前后%的拼接

/**
* 模糊查询
*/
@Test
public void testSeach() throws Exception {
//1.导入jar包
//2.加载驱动
Class.forName(driver);
//3.获取数据库连接
Connection con = DriverManager.getConnection(url, username, password);
//4.获取预处理对象
String sql="select * from student where stuName like ?";
PreparedStatement pstm = con.prepareStatement(sql);
//5.传参并执行sql
String keyword="a"; //后期是通过页面获取用户输入的关键词
pstm.setObject(1,"%"+keyword+"%"); //对关键词进行前后%的拼接
ResultSet rs = pstm.executeQuery();
//6.解析结果集,模糊查询有可能查到很多条数据,所以定义集合存储
List<Student> studentList=new ArrayList<>();
while (rs.next()){
Student student=new Student();
//通过rs根据字段名获取数据库表中的数据,然后把数据封装到Student对象中
student.setStuId(rs.getInt("stuId"));
student.setStuName(rs.getString("stuName"));
student.setStuSex(rs.getString("stuSex"));
student.setStuAge(rs.getInt("stuAge"));
student.setStuAddr(rs.getString("stuAddr"));
//把当前的student对象存储到list集合中
studentList.add(student);
}
//打印输出
System.out.println(studentList);
//7.资源的释放
if(rs!=null){
rs.close();
}
if(pstm!=null){
pstm.close();
}
if(con!=null){
con.close();
}
}

5.2 模糊查询的进阶版代码如下:

在mysql中 concat() 函数使用来做字符串的拼接; select * from student where stuName like concat('%',?,'%') 的意思就是自动给 ? 拼接前后的 % ; 那么在传参的时候直接把关键词传参给 ? 即可,不在需要在传参的时候进行拼接。 String keyword="a"; //后期是通过页面获取用户输入的关键词 pstm.setObject(1,keyword); //直接把关键词传参给预处理对象的 

/**
* 模糊查询
*/
@Test
public void testSeach() throws Exception {
//1.导入jar包
//2.加载驱动
Class.forName(driver);
//3.获取数据库连接
Connection con = DriverManager.getConnection(url, username, password);
//4.获取预处理对象
String sql="select * from student where stuName like concat('%',?,'%')";
PreparedStatement pstm = con.prepareStatement(sql);
//5.传参并执行sql
String keyword="a"; //后期是通过页面获取用户输入的关键词
pstm.setObject(1,keyword);
ResultSet rs = pstm.executeQuery(); //直接把关键词传参给预处理对象的 ?
//6.解析结果集,模糊查询有可能查到很多条数据,所以定义集合存储
List<Student> studentList=new ArrayList<>();
while (rs.next()){
Student student=new Student();
//通过rs根据字段名获取数据库表中的数据,然后把数据封装到Student对象中
student.setStuId(rs.getInt("stuId"));
student.setStuName(rs.getString("stuName"));
student.setStuSex(rs.getString("stuSex"));
student.setStuAge(rs.getInt("stuAge"));
student.setStuAddr(rs.getString("stuAddr"));
//把当前的student对象存储到list集合中
studentList.add(student);
}
//打印输出
System.out.println(studentList);
//7.资源的释放
if(rs!=null){
rs.close();
}
if(pstm!=null){
pstm.close();
}
if(con!=null){
con.close();
}
}

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
JDBCJava Database Connectivity)是一种用于执行SQL语句的Java API,它提供了一种连接到数据库的标准方式。下面是JDBC增删改查的详细步骤: 1. 加载JDBC驱动程序 在使用JDBC之前,必须加载适合于数据库JDBC驱动程序。不同的数据库有不同的JDBC驱动程序,因此你需要根据你使用的数据库加载相应的驱动程序。例如: ``` Class.forName("com.mysql.jdbc.Driver"); ``` 2. 建立数据库连接 在加载完JDBC驱动程序之后,就可以建立与数据库之间的连接了。连接的过程需要提供数据库的URL、用户名和密码。例如: ``` String url = "jdbc:mysql://localhost:3306/test?useSSL=false"; String user = "root"; String password = "123456"; Connection connection = DriverManager.getConnection(url, user, password); ``` 3. 创建Statement对象 在建立好数据库连接之后,就可以创建一个Statement对象。Statement对象用于执行SQL语句并返回结果。例如: ``` Statement statement = connection.createStatement(); ``` 4. 执行SQL语句 接下来,可以使用Statement对象执行SQL语句。例如: ``` String sql = "SELECT * FROM user"; ResultSet resultSet = statement.executeQuery(sql); ``` 如果要执行增、删、改操作,则可以使用Statement对象的executeUpdate()方法。例如: ``` String sql = "INSERT INTO user(name, age) VALUES('张三', 20)"; statement.executeUpdate(sql); ``` 5. 处理结果集 如果执行的是查询操作,则需要处理查询结果集。查询结果集以ResultSet对象的形式返回。例如: ``` while (resultSet.next()) { String name = resultSet.getString("name"); int age = resultSet.getInt("age"); System.out.println("name: " + name + ", age: " + age); } ``` 6. 关闭连接 在完成JDBC操作之后,需要关闭与数据库的连接。例如: ``` resultSet.close(); statement.close(); connection.close(); ``` 以上就是JDBC增删改查的详细步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夜未柒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值