JDBC复习

发布于:2022-11-27 ⋅ 阅读:(226) ⋅ 点赞:(0)

1.什么是JDBC


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

2.创建数据库


JDBC操作数据库的步骤:


1.首先在项目根目录创建lib文件夹,放入jdbc驱动程序,然后Add As Library

2.加载数据库驱动

3.使用驱动管理器来获得连接---获得一个数据库连接对象Connection

4.使用Connection创建PreparedStatement语句对象---PreparedStatement对象可以执行sql语句

5.使用PreparedStatement对象执行SQL语句

6.操作判断--增删改返回的是影响的行数(返回值是int),只有查询获得结果集(返回值ResultSet)

7.回收资源


2.1数据类型

java共有八种数据类型:

整数类型:byte  short  int  long

浮点类型:float  double

字符类型:char

布尔类型:boolean


数据类型

数值型:  int  float  double

字符型:varchar(可变的)   char(固定的)

日期类型:datetime


char用于存储单个字符,如:性别  '男'  '女',电灯  '开' '关'

int用于存储整数,如:一天的时间是24小时,一月份有31天

double用于存储小数,如:酸奶的价格3.5元

String用于存储一串字符,如:"我的爱好是踢足球2"


2.2类

类:

DriverManager:

作用:获取连接(DriverManager.getConnection(url, username, password));

Connection:

作用:获取执行sql语句的对象(prepareStatement(String  sql));

PrepareStatement:

作用:执行sql语句

方法:查询语句 executeQuery()

ResultSet     结果集

方法:next():    判断下一个是否有元素                                                                                                               根据表的列名和数据类型获取对应的值


创建学生信息表

-- 设置数据的视图 
-- 使用数据库
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('lisa','女',20,'泰国');
insert into student(stuName,stuSex,stuAge,stuAddr) values('张三','男',20,'河南');
insert into student(stuName,stuSex,stuAge,stuAddr) values('娜塔莎','女',19,'俄罗斯');
insert into student(stuName,stuSex,stuAge,stuAddr) values('威廉','男',20,'美国');

-- 查询数据表
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;

   ......

3.2JDBC的查询操作


查询数据

select   字段名1,字段2, .....字段名n     from

表名

查询所有的字段用*代替


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的全查的源码如下:

//全查
    @Test
    public void testSelectAll() throws ClassNotFoundException, SQLException {
        //加载数据库驱动
        Class.forName(driver);
        //使用驱动器管理器来获得连接--获得一个数据连接数据库对象Connerction
        Connection con = DriverManager.getConnection(url, username, password);
        //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<>();
        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.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){
            pstm.close();
        }
    }

添加数据

insert   into   表名    values(值1,值2,值3...值n);

:必须注入全部字段。

3.3JDBC的添加操作

 @Test
    //添加
    public void testAdd() throws ClassNotFoundException, SQLException {
        //2.加载数据库驱动
        Class.forName(driver);
        //3.使用驱动管理器来获得连接---获得一个数据库连接对象Connection
        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("rose");
        student.setStuSex("女");
        student.setStuAge(18);
        student.setStuAddr("新西兰");

        //预处理对象的sql语句有 ? 所以需要进行传参
        pstm.setObject(1,student.getStuName());
        pstm.setObject(2,student.getStuSex());
        pstm.setObject(3,student.getStuAge());
        pstm.setObject(4,student.getStuAddr());

        //执行更新(增删改都叫做数据库的更新,更新返回的是影响的行数)
        int i = pstm.executeUpdate();
        //判断影响的行数 n > 0 表示插入成功,否则插入失败
        if(i>0){
            System.out.println("插入数据成功");
        }else {
            System.out.println("插入数据失败");
        }

        //释放资源
        if(pstm!=null){
            pstm.close();
        }
        if(con!=null){
            con.close();
        }
    }

删除数据

delete from 表名 [where  条件表达式]

3.4JDBC的删除操作

@Test
    //删除
    public void tesDel() throws ClassNotFoundException, SQLException {
        //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 i = pstm.executeUpdate();
        //6判断影响的行数 n>0 表示删除成功,否则删除失败
        if(i>0){
            System.out.println("删除成功");
        }else {
            System.out.println("删除失败");
        }
        //7释放资源
        if(pstm!=null){
            pstm.close();
        }
        if(con!=null){
            con.close();
        }
    }

3.5JDBC的修改操作


修改的逻辑:
点击按钮后执行的步骤:
1. 先根据 id 查询数据库中原始数据;
2. 根据需要修改部分字段;
3. 把最新的数据执行数据库的更新操作。

修改数据
update  表名  set  字段名1=值1,...字段名n=值n[where  条件表达式] 

完成根据id查询学生信息的代码
public Student selectById(int id) throws ClassNotFoundException, SQLException {
        //JDBC操作数据库的步骤
        //1.首先在项目根目录创建lib文件夹,放入jdbc驱动程序,然后Add As Library
        //2.加载数据库驱动,使用反射加载
        Class.forName(driver);
        //3.使用驱动管理器来获得连接--获得一个数据库连接对象Connection
        Connection con = DriverManager.getConnection(url, username, password);
        //4.使用Connection创建PreparedStatement预处理对象--PreparedStatement对象可以对sql语句预处理,sql可以带?
        String sql="select * from student where stuId=?";
        PreparedStatement pstm = con.prepareStatement(sql);
        //5.使用PreparedStatement对象执行sql语句,查询返回的是结果集,增删返回的是影响的行数(int)
        pstm.setObject(1,id);
        ResultSet rs = pstm.executeQuery();
        //6.操作判断--增删该返回的是影响的行数(返回值是int),只有查询获得结果集(返回值ResultSet)
        //ResultSet结果集的游标默认指向的是表的标题行,需要让游标向下移动指向数据行。
        Student student=null;
        if(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=new Student();
            student.setStuId(stuId);
            student.setStuName(stuName);
            student.setStuSex(stuSex);
            student.setStuAge(stuAge);
            student.setStuAddr(stuAddr);
        }
        //7.回收资源
        if(rs!=null){
            rs.close();
        }
        if(pstm!=null){
            pstm.close();
        }
        if(con!=null){
            con.close();
        }
       return student;
    }

完成修改操作的测试代码

@Test
    public void testUpdate() throws SQLException, ClassNotFoundException {
        //第一步:根据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("请修改年龄:");
        int newAge = sc.nextInt();
        student.setStuAge(newAge);

        System.out.println("请修改地址:");
        String newAddr = sc.next();
        student.setStuAddr(newAddr);

        System.out.println("修改后:"+student);

        //第三步:修改 字段值后把最新的数据执行数据库JDBCd的修改操作
        //1.导入jar包
        //2.使用反射加载驱动程序
        Class.forName(driver);
        //3.使用驱动管理器获得数据库的连接
        Connection con = DriverManager.getConnection(url, username, 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 i = pstm.executeUpdate();
        //6.判断执行结果
        if(i>0){
            System.out.println("修改成功");
        }else {
            System.out.println("修改失败");
        }
        //7.
        if(pstm!=null){
            pstm.close();
        }
        if(con!=null){
            con.close();
        }
    }

3.6JDBC的模糊查询

模糊查询一般是通过一个输入框输入的关键字,然后点击搜索进行检索,执行的是数据的模糊查询; 

语句示例:select * from student where stuName like '%关键词%';

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

因为sql语句是select * from student where stuName like ?;

所以传参的时候需要对关键词进行前后%的拼接:                                                                                      String keyword="a"; //后期是通过页面获取用户输入的关键词                                                  pstm.setObject(1,"%"+keyword+"%"); //对关键词进行前后%的拼接        

模糊查询   like

%:代表0或多个

       张%:获取姓张(以张开头)

       %张%:获取包含张的

       %张:获取以张结尾的

       _:占位符

       张_:两个字符的名字   第一个字为张

  @Test
    public void testSeach() throws ClassNotFoundException, SQLException {
        //加载数据库驱动
        Class.forName(driver);
        //使用驱动器管理器来获得连接--获得一个数据连接数据库对象Connerction
        Connection con = DriverManager.getConnection(url, username, password);
        //4.使用Connection创建PreparedStatement预处理对象---PreparedStatement对象可以执行带 ? 的sql语句
        String sql = "select * from student where stuName like ?";
        PreparedStatement pstm = con.prepareStatement(sql);
        //5.使用PreparedStatement对象执行SQL语句,获得ResultSet结果集对象
        String keyword="a";//后期是通过页面获取用户输入的关键词
        pstm.setObject(1,"%"+keyword+"%");//对关键此进前后%的拼接
        ResultSet rs = pstm.executeQuery();
        //6.操作判断--增删改返回的是影响的行数(返回值是int),只有查询获得结果集(返回值ResultSet)
        //让结果集的游标不断的往下移动,直到没有数据的时候结束循环
        List<Student> StudentList = new ArrayList<>();
        while (rs.next()) {
            //通过rs根据字段名获取数据库表中的数据,然后把数据封装到Student对象中
            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.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();
        }
    }
  模糊查询的进阶版代码如下:
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();
}
}

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到