Know JDBC and JDBC connection database, add, delete, modify and check operations

1. What is JDBC

Concept: Java Database Connectivity, ( Java Database Connectivity , JDBC for short ) is used in the Java language to standardize client programs
How to access the application program interface of the database , providing methods such as querying and updating data in the database. JDBC is also Sun
Trademark of Microsystems . The JDBC we usually say is oriented to relational databases.
Each database manufacturer implements the function code of its own database operation according to the JDBC specification, and then uses the jar package (the driver provided by the database manufacturer)
package) for developers to use, and developers use the reflection mechanism to create these concrete implementation classes, and complete them according to the JDBC specification
into database operations.

1.1  Understanding of interface and JDBC specification:

1.2 Commonly used interfaces and classes of JDBC:

DriverManager: This class manages the list of database drivers and checks whether the loaded driver complies with the JAVA Driver API specification

Connection: communicate with the database through the connection object in the database

Statement: Store the created SQL object in the database instead

ResultSet: It is an iterator for retrieving query data

1.3 JDBC advantages and disadvantages:

advantage:

1. JDBC frees programmers from complex driver call commands and functions, and can focus on key places in the application.

2. JDBC supports different relational databases, which greatly enhances the portability of the program.

3. JDBC API is object-oriented, allowing users to encapsulate common methods into a class for later use.

shortcoming:

1. Using JDBC, the speed of accessing data records will be affected to a certain extent.

2. The JDBC structure contains products from different manufacturers, which brings a lot of trouble to changing the data source.

1.4 Main tasks:

JDBC technology mainly completes the following tasks:

1. Establish a link with the database

2. Send SQL statement to the database

3. Process the results returned from the database

1.5 JDBC steps six steps (focus)

Step 1: Load the driver (the jar package [driver package] should be introduced into the project)

Step 2: Use DriverManager to establish a connection between the program and the database (indicating that the channel between the JVM process and the database process is opened, which belongs to the communication between processes)

Step 3: Obtain the database operation object (the object that specifically executes the sql statement)

Step 4: Execute sql statement (DQL, DML...)

Step 5: Process the query result set (the query result set needs to be processed only when the DQL query statement is executed)

Step 6: Close the resource (be sure to close the resource after use)

2. JDBC connection to the database and addition, deletion, modification and query operations

 Junit can make the method execute directly from the main method, which is convenient for program testing.

Junit usage: 1. The method should be defined as having no parameters and no return value. And the name of the test class cannot be Test
           2. Use the @Test annotation on the method
           3. Put the cursor on the back, then use alt + enter to automatically import the package, select---Add 'JUnit4' to classpath
           4. This method can be executed without relying on the main method

2.1 Create a database

2.1.1 Create a database

CREATE DATABASE demo;

2.1.2 Create a table named student

CREATE TABLE student(
	stuId INT PRIMARY KEY AUTO_INCREMENT,
	stuName VARCHAR(16),
	stuSex VARCHAR(4),
	stuAge INT,
	stuAddr VARCHAR(32)
);

The result of running the code is as follows: 

 2.1.3 Insert data into the table

INSERT INTO student(stuName,stuSex,stuAge,stuAddr)VALUES('陈格','女',19,'信阳');
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,'信阳');

The result of running the code is as follows: 

2.2 Use JDBC to operate on the database

2.2.1 First create an entity class in IDEA: the class name corresponds to the name of the table in the database, and the attributes of the class correspond to the fields of the table

    // Automatically construct code shortcut keys: alt + insert

public class Student {
    //类的属性
    private int stuId;
    private String stuName;
    private String stuSex;
    private int stuAge;
    private String stuAddr;

    //自动构造代码快捷键: alt + insert

    //无参构造函数
    public Student() {
    }

    //有参构造函数
    public int getStuId() {
        return stuId;
    }

    public void setStuId(int stuId) {
        this.stuId = stuId;
    }

    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    public String getStuSex() {
        return stuSex;
    }

    public void setStuSex(String stuSex) {
        this.stuSex = stuSex;
    }

    public int getStuAge() {
        return stuAge;
    }

    public void setStuAge(int stuAge) {
        this.stuAge = stuAge;
    }

    public String getStuAddr() {
        return stuAddr;
    }

    public void setStuAddr(String stuAddr) {
        this.stuAddr = stuAddr;
    }

    @Override
    public String toString() {
        return "student{" +
                "stuId=" + stuId +
                ", stuName='" + stuName + '\'' +
                ", stuSex='" + stuSex + '\'' +
                ", stuAge=" + stuAge +
                ", stuAddr='" + stuAddr + '\'' +
                '}';
    }
}
The four parameters that need to be configured to connect to the database, and the jar package needs to be driven at the same time

Create a lib folder in the project root directory, put the jdbc driver, and then Add As Library

The driver package is searched on the official website

​Download link of mysql-connector-java-8.0.23.jar: The download link
expires after one year from the server. If it expires, use Baidu Netdisk to download it first.


Link: https://pan.baidu.com/s/187wdM_EU_Nc8adLdMnwUoQ?pwd=1111 
Extraction code:
1111

 

//communication protocol database server address: local machine address MySQL port number database name account password

 jdbc:mysql://127.0.0.1:                                  3306/               demo",      "root",     "root"

 2.2.2 Full search operation

public void testSelctAll() throws Exception {
        //JDBC操作数据库的步骤
        //1.首先在项目根目录创建lib文件夹,放入jdbc驱动程序,然后Add As Library

        //2.加载驱动程序
        Class.forName("com.mysql.cj.jdbc.Driver");

        //3.使用DriverManager建立程序与数据库的连接
        Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/demo","root","root");

        //4.使用Connection创建PreparedStatement预处理对象--PreparedStatement对象可以对sql语句预处理
        String sql = "select * from student";
        PreparedStatement pstm = conn.prepareStatement(sql);

        //5.使用PreparedStatement对象执行sql语句,查询返回的是结果集,增删改返回的是影响的行数(int)
        ResultSet rs = pstm.executeQuery();

        //ResultSet 结果集的游标默认指向的是表的标题,需要让游标向下移动指向数据行

        //6.操作判断--增删改返回的是影响的行数(返回值是int),只有查询获得结果集(返回值ResultSet)
        //定义一个集合,用来存储每一行的数据(封装在了Student对象中)
        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);
        }
      for (Student c :studentList){
          System.out.println(c.toString());
      }

        //7.回收资源
        if (rs!=null){
            rs.close();
        }
        if (pstm!=null){
            pstm.close();
        }
        if (conn!=null){
            conn.close();
        }
    }

 

 

2.2.3 Add--add data

  @Test
    public  void  testAdd() throws Exception {
        //1.导入驱动包
        //2.加载驱动程序
        Class.forName("com.mysql.cj.jdbc.Driver");

        //3.使用DriverManager建立程序与数据库的连接
        Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/demo","root","root");

        //4.使用Connection创建PreparedStatement预处理对象
        String sql = "insert into student(stuName,stuSex,stuAge,stuAddr) values(?,?,?,?)";
        PreparedStatement pstm = conn.prepareStatement(sql);

        // 构造数据,数据封装在Student对象中
        Student student = new Student();
        student.setStuName("小张");
        student.setStuSex("女");
        student.setStuAge(20);
        student.setStuAddr("河北");

        //5.1传参
        pstm.setObject(1,student.getStuName());
        pstm.setObject(2,student.getStuSex());
        pstm.setObject(3,student.getStuAge());
        pstm.setObject(4,student.getStuAddr());
        //5.2执行更新 (更新操作)
        int c = pstm.executeUpdate();

        //6.判断受影响的行数,如果n>0 表示添加成功,否则添加失败
        if (c>0){
            System.out.println("添加成功");
        }else{
            System.out.println("添加失败");
        }

        //7.资源回收
        if (pstm != null){
            pstm.close();
        }
        if (conn != null){
            conn.close();
        }
    }

 

 

 

2.2.4 Delete--delete data

  @Test
    public  void  testDelete() throws Exception {
        //1.导入驱动包
        //2.加载驱动程序
        Class.forName("com.mysql.cj.jdbc.Driver");

        //3.使用DriverManager建立程序与数据库的连接
        Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/demo","root","root");

        //4.使用Connection创建PreparedStatement预处理对象
        String sql = "delete  from  student where stuId = ?";
        PreparedStatement pstm = conn.prepareStatement(sql);

        //5.1执行?的传参
        int stuId  = 2;
        pstm.setObject(1,stuId);
        //5.2执行数据的更新 (更新操作)
        int c = pstm.executeUpdate();

        //6.判断受影响的行数,如果n>0 表示添加成功,否则添加失败
        if (c>0){
            System.out.println("删除成功");
        }else{
            System.out.println("删除失败");
        }

        //7.资源回收
        if (pstm != null){
            pstm.close();
        }
        if (conn != null){
            conn.close();
        }
    }

 

 

 

2.2.5 Change--modify data

  @Test
    public  void  testUpdate() throws Exception {
        //1.导入驱动包
        //2.加载驱动程序
        Class.forName("com.mysql.cj.jdbc.Driver");

        //3.使用DriverManager建立程序与数据库的连接
        Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/demo","root","root");

        //4.使用Connection创建PreparedStatement预处理对象
        String sql = "update student set stuName = ?,stuSex = ? where stuId = ?";
        PreparedStatement pstm = conn.prepareStatement(sql);

        //5.1执行?的传参
        pstm.setInt(3,4);
        pstm.setString(1,"张玉");
        pstm.setString(2,"女");
        //5.2执行数据的更新 (更新操作)
        int c = pstm.executeUpdate();

        //6.判断受影响的行数,如果n>0 表示添加成功,否则添加失败
        if (c>0){
            System.out.println("修改成功");
        }else{
            System.out.println("修改失败");
        }

        //7.资源回收
        if (pstm != null){
            pstm.close();
        }
        if (conn != null){
            conn.close();
        }
    }
}

 

 

 

 Overall code:

package com.hp.test02;

import com.hp.bean.Student;
import org.junit.Test;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class StudentTest {

    /**
     * 数据库的查询操作
     */
    @Test
    public void testSelctAll() throws Exception {
        //JDBC操作数据库的步骤
        //1.首先在项目根目录创建lib文件夹,放入jdbc驱动程序,然后Add As Library

        //2.加载驱动程序
        Class.forName("com.mysql.cj.jdbc.Driver");

        //3.使用DriverManager建立程序与数据库的连接
        Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/demo","root","root");

        //4.使用Connection创建PreparedStatement预处理对象--PreparedStatement对象可以对sql语句预处理
        String sql = "select * from student";
        PreparedStatement pstm = conn.prepareStatement(sql);

        //5.使用PreparedStatement对象执行sql语句,查询返回的是结果集,增删改返回的是影响的行数(int)
        ResultSet rs = pstm.executeQuery();

        //ResultSet 结果集的游标默认指向的是表的标题,需要让游标向下移动指向数据行

        //6.操作判断--增删改返回的是影响的行数(返回值是int),只有查询获得结果集(返回值ResultSet)
        //定义一个集合,用来存储每一行的数据(封装在了Student对象中)
        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);
        }
      for (Student c :studentList){
          System.out.println(c.toString());
      }

        //7.回收资源
        if (rs!=null){
            rs.close();
        }
        if (pstm!=null){
            pstm.close();
        }
        if (conn!=null){
            conn.close();
        }
    }
    /**
     * 数据库的增加操作
     */
    @Test
    public  void  testAdd() throws Exception {
        //1.导入驱动包
        //2.加载驱动程序
        Class.forName("com.mysql.cj.jdbc.Driver");

        //3.使用DriverManager建立程序与数据库的连接
        Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/demo","root","root");

        //4.使用Connection创建PreparedStatement预处理对象
        String sql = "insert into student(stuName,stuSex,stuAge,stuAddr) values(?,?,?,?)";
        PreparedStatement pstm = conn.prepareStatement(sql);

        // 构造数据,数据封装在Student对象中
        Student student = new Student();
        student.setStuName("小张");
        student.setStuSex("女");
        student.setStuAge(20);
        student.setStuAddr("河北");

        //5.1传参
        pstm.setObject(1,student.getStuName());
        pstm.setObject(2,student.getStuSex());
        pstm.setObject(3,student.getStuAge());
        pstm.setObject(4,student.getStuAddr());
        //5.2执行更新 (更新操作)
        int c = pstm.executeUpdate();

        //6.判断受影响的行数,如果n>0 表示添加成功,否则添加失败
        if (c>0){
            System.out.println("添加成功");
        }else{
            System.out.println("添加失败");
        }

        //7.资源回收
        if (pstm != null){
            pstm.close();
        }
        if (conn != null){
            conn.close();
        }
    }

    /**
     * 数据库的删除操作
     */
    @Test
    public  void  testDelete() throws Exception {
        //1.导入驱动包
        //2.加载驱动程序
        Class.forName("com.mysql.cj.jdbc.Driver");

        //3.使用DriverManager建立程序与数据库的连接
        Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/demo","root","root");

        //4.使用Connection创建PreparedStatement预处理对象
        String sql = "delete  from  student where stuId = ?";
        PreparedStatement pstm = conn.prepareStatement(sql);

        //5.1执行?的传参
        int stuId  = 2;
        pstm.setObject(1,stuId);
        //5.2执行数据的更新 (更新操作)
        int c = pstm.executeUpdate();

        //6.判断受影响的行数,如果n>0 表示添加成功,否则添加失败
        if (c>0){
            System.out.println("删除成功");
        }else{
            System.out.println("删除失败");
        }

        //7.资源回收
        if (pstm != null){
            pstm.close();
        }
        if (conn != null){
            conn.close();
        }
    }

    /**
     * 数据库的修改操作
     */
    @Test
    public  void  testUpdate() throws Exception {
        //1.导入驱动包
        //2.加载驱动程序
        Class.forName("com.mysql.cj.jdbc.Driver");

        //3.使用DriverManager建立程序与数据库的连接
        Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/demo","root","root");

        //4.使用Connection创建PreparedStatement预处理对象
        String sql = "update student set stuName = ?,stuSex = ? where stuId = ?";
        PreparedStatement pstm = conn.prepareStatement(sql);

        //5.1执行?的传参
        pstm.setInt(3,4);
        pstm.setString(1,"张玉");
        pstm.setString(2,"女");
        //5.2执行数据的更新 (更新操作)
        int c = pstm.executeUpdate();

        //6.判断受影响的行数,如果n>0 表示添加成功,否则添加失败
        if (c>0){
            System.out.println("修改成功");
        }else{
            System.out.println("修改失败");
        }

        //7.资源回收
        if (pstm != null){
            pstm.close();
        }
        if (conn != null){
            conn.close();
        }
    }
}

Guess you like

Origin blog.csdn.net/weixin_67224308/article/details/127600292