Detailed explanation of the nature and use of JDBC in Java

Preface

I personally think that JDBC is more important in the study of Java, which realizes the interaction between the database and the Java code, so I still write an article to consolidate it.

This article mainly solves the following questions
1. What is JDBC (first acquaintance)?
2. What is the essence of JDBC?
3. How to use JDBC (beginner, easy to understand)?

One, JDBC overview

In order to provide support for database access in the Java language, Sun provided a set of standard Java library JDBC for database access in 1996. The full name of JDBC is Java Database Connectivity (Java Database Connectivity), which is a set of Java APIs used to execute SQL statements. Applications can connect to the relational database through this set of APIs to complete operations such as querying, updating, and deleting data in the database.

Second, the essence of JDBC

JDBC is a set of interfaces developed by SUN. The
purpose: Decoupling——>Reduce the coupling degree of the program and improve the expansion power of the program

3. For the relationship between JDBC and database driver, please refer to the figure below:

Insert picture description here

Four, about the six-step overview of JDBC programming

1. Graphic

Insert picture description here

2. Overview

The first step: load the driver (function: tell the Java program to connect to the database of that brand)

Load the database driver by reflection, the code is as follows:

Class.forName(“com.mysql.jdbc.Driver”);

Step 2: Create a connection (indicating that the channel between the JVM process and the database process is open)

Use the getConnection() method in the java.sql.Drivermanager class to establish a connection with the database.

DriverManager.getConnection(“jdbc:mysql://数据库地址:端口号/数据库名”,”用户名”, “密码”);

The third step: Obtain the database operation object (the object that executes the sql statement) and
use java.sql.Connection to create the Statement used to execute the SQL statement. (It is recommended to use preparedStatement, a subclass of Statement)

Statement statement = connection.createStatement();

Step 4: Execute sql statement
Use java.sql.Statement to execute SQL statement. The commonly used method is as follows:
execute(String sql) This method can execute any SQL statement. This method returns true if and only if the select statement is executed and there is a return result. In other cases, the method returns false.
executeUpdate(String sql) This method is often used to execute DML (INSERT, UPDATE or DELETE) and DDL statements. The number of rows affected by the SQL statement is returned when the DML statement is executed, and 0 is returned when the DDL statement is executed.
executeQuery(String sql) This method usually executes the query statement and returns the ResultSet object representing the result set after execution.

ResultSet  resultSet = statement.executeQuery(sql);

Step 5: Process the query result set (only when the query statement is executed in the fourth step, the result set will be processed)

After getting the data in the database from the ResultSet, we encapsulate the data in JavaBean. Please pay attention to the correspondence between Java data types and database data types:

Types of data in the database Java data types
int int
smallint short
bigint long
tityint byte
float float
double double
charvarchar String
date Date

Step 6: Release resources (resources need to be closed after use. Java and the database belong to the communication between processes, and must be closed after opening)
database resources are very precious, and the number of concurrent access connections allowed by the database is limited. Therefore, remember to release the resources when the database resources are used up. In order to ensure the release of resources, resources related to database operations are often closed in the finally code block.

Five, six steps of JDBC programming (code demonstration)

Please add the jar package required by MySQL (for example: mysql-connector-java-5.1.7-bin.jar) to the lib folder of the Java project and execute Build Path, as shown in the following figure:
Insert picture description here

1. The JDBC instance that needs to process the query result set (when the executed sql statement is a query statement)

1.1 Create a student table in the database mydb and store the data

The sql command is as follows (create a student table in the database mydb and store the data):

-- 若存在数据库mydb则删除
DROP DATABASE IF EXISTS mydb;
-- 创建数据库mydb
CREATE DATABASE mydb;
-- 选择数据库mydb
USE mydb;

-- 创建学生表
CREATE TABLE student (
     studentid INT,
   studentname VARCHAR(50)
);

-- 向学生表插入数据
INSERT INTO student (studentid,studentname) VALUES (1,"张三");
INSERT INTO student (studentid,studentname) VALUES (2,"李四");
INSERT INTO student (studentid,studentname) VALUES (3,"王五");
INSERT INTO student (studentid,studentname) VALUES (4,"赵六");

The results of DOS window operation are as follows:
Insert picture description here

1.2 Create a JavaBean of the student class (the elements inside are the same as the field information type of the student table in the database)

The code is as follows (JavaBean of the student class):

public class Student {
    
    
	private int studentID;
	private String studentName;
	public Student() {
    
    
		super();
		// TODO Auto-generated constructor stub
	}
	public Student(int studentID, String studentName) {
    
    
		super();
		this.studentID = studentID;
		this.studentName = studentName;
	}
	public int getStudentID() {
    
    
		return studentID;
	}
	public void setStudentID(int studentID) {
    
    
		this.studentID = studentID;
	}
	public String getStudentName() {
    
    
		return studentName;
	}
	public void setStudentName(String studentName) {
    
    
		this.studentName = studentName;
	}
	@Override
	public String toString() {
    
    
		return "Student [studentID=" + studentID + ", studentName=" + studentName + "]";
	}
}

1.3 Use JDBC to operate the database (query all student information)

The code is as follows (example):

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCSelectTest {
    
    

	public static void main(String[] args) {
    
    
		JDBCSelectTest jdbcSelectTest = new JDBCSelectTest();
		jdbcSelectTest.findAllStudent();

	}

	private void findAllStudent() {
    
    
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		try {
    
    
			// 1、启动驱动
			Class.forName("com.mysql.jdbc.Driver");
			// 2、建立连接
			connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "123456");
			// 3、获取数据库操作对象
			String sql = "select * from student";
			preparedStatement = connection.prepareStatement(sql);
			// 4、执行sql语句
			resultSet = preparedStatement.executeQuery();
			// 5、处理结果集
			while (resultSet.next()) {
    
    
				Student student = new Student();
				int id = resultSet.getInt("studentid");
				String name = resultSet.getString("studentname");
				student.setStudentID(id);
				student.setStudentName(name);
				System.out.println(student);
			}
		} catch (Exception e) {
    
    
			e.printStackTrace();
		} finally {
    
    
			// 6、关闭资源
			if (resultSet != null) {
    
    
				try {
    
    
					resultSet.close();
				} catch (SQLException e) {
    
    
					e.printStackTrace();
				}
				resultSet = null;
			}

			if (preparedStatement != null) {
    
    
				try {
    
    
					preparedStatement.close();
				} catch (SQLException e) {
    
    
					e.printStackTrace();
				}
				preparedStatement = null;
			}

			if (connection != null) {
    
    
				try {
    
    
					connection.close();
				} catch (SQLException e) {
    
    
					e.printStackTrace();
				}
				connection = null;
			}
		}
	}
}

The code is as follows (output):

Student [studentID=1, studentName=张三]
Student [studentID=2, studentName=李四]
Student [studentID=3, studentName=王五]
Student [studentID=4, studentName=赵六]

2. The JDBC instance that does not need to process the query result set (the SQL statement executed is for adding, deleting, or modifying)

For JavaBeans and data tables, I just continue to use the ones prepared above.
Here I only demonstrate "increase" (that is, add a piece of data to the student table), the other basic processes of "delete" and "change" are the same, only the sql statement and the position of the station symbol are different, leaving you free to explore

The code is as follows (example):

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JDBCAddTest {
    
    

	public static void main(String[] args) {
    
    
		JDBCAddTest jdbcAddTest = new JDBCAddTest();
		jdbcAddTest.addStudent();

	}

	private void addStudent() {
    
    
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		try {
    
    
			// 1、启动驱动
			Class.forName("com.mysql.jdbc.Driver");
			// 2、建立连接
			connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "123456");
			// 3、获取数据库操作对象
			Student student = new Student(5, "jack");
			String sql = "insert into student values(?,?)";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(2, student.getStudentName());
			preparedStatement.setInt(1, student.getStudentID());
			// 4、执行sql语句
			int executeUpdate = preparedStatement.executeUpdate();
			System.out.println(executeUpdate);
		} catch (Exception e) {
    
    
			e.printStackTrace();
		} finally {
    
    
			// 6、关闭资源
			if (preparedStatement != null) {
    
    
				try {
    
    
					preparedStatement.close();
				} catch (SQLException e) {
    
    
					e.printStackTrace();
				}
				preparedStatement = null;
			}

			if (connection != null) {
    
    
				try {
    
    
					connection.close();
				} catch (SQLException e) {
    
    
					e.printStackTrace();
				}
				connection = null;
			}
		}
		
	}

}

The code is as follows (output):

The 1 output here means that one piece of data in the database is affected

1

To be safe, check the student table in the database
Insert picture description here

to sum up

It should be noted that in the fifth step, when the SQL statement is executed, the execution query is preparedStatement.executeQuery() , and the other three operations are **preparedStatement.executeUpdate()** For those who are just starting to learn, special attention is needed.

For the extension of JDBC, please refer to the following articles:

1. Database connection pool-DBCP, C3P0 (don't miss it when you pass by!!!)

2. DbUtils framework (this is a time-consuming and labor-intensive task)

Guess you like

Origin blog.csdn.net/weixin_45851945/article/details/114967746