MySQL database --- Java JDBC programming

JDBC Programming in Java

1. Prerequisites for database programming

  • Programming language: such as Java, C, C++, Python, etc.
  • Database: such as Oracle, MySQL, SQL Server, etc.
  • Database driver package: Different databases provide different database driver packages corresponding to different programming languages.
    For example, MySQL provides a Java driver package mysql-connector-java, which is required to operate MySQL based on Java. Similarly, to operate Oracle database based on Java, Oracle's database driver package ojdbc is required.

2. MySQL driver package installation

  1. First browser search https://mvnrepository.com

  2. Search for mysql jdbc in the input box
    insert image description here

  3. Find this one below and click on it
    insert image description here

  4. Select the driver corresponding to your mysql version
    insert image description here

  5. Choose a click to download
    insert image description here

3. Deployment of driver package in idea

  1. First, in the idea project, create a directory, and then copy the jar package into it
    insert image description here
    insert image description here
    insert image description here

  2. Open the idea in the upper left corner File -> Project Structure…
    insert image description here

  3. Click on Librarires -> + -> Java
    insert image description here

  4. Then select the libs directory and go all the way to ok
    insert image description here

4. Database programming in Java: JDBC

Because there are many types of databases, the API (application programming interface) provided by different databases is not the same. In order to solve this problem in Java, JDBC is introduced.

JDBC, ie Java Database Connectivity, java database connection. Is a Java API for executing SQL statements, which is the database connection specification in Java. This API consists java.sql.*of javax.sql.*some classes and interfaces in the package. It provides a standard API for Java developers to manipulate databases and can provide unified access to various relational databases.

Convert different kinds of APIs to a JDBC-style unified API through different database drivers

In Java such a driver is a standalonejar包

JDBC advantages:

  1. Java language access database operation is completely oriented to abstract interface programming
  2. The development of database applications is not limited to the API of a specific database vendor
  3. Program portability is greatly enhanced

5. JDBC API

In Java JDBC programming, database operations are handled uniformly using the JDK's own API, which is usually completely decoupled from the driver class of a specific database. So master the Java JDBC API (located in the java.sql package) to master Java database programming.

6. JDBC common interfaces and classes

6.1 Database Connection Connection

The connection interface implementation class is provided by the database. There are usually two ways to obtain the Connection object:
one is to obtain it through the static method of the DriverManager (driver management class):

// 加载JDBC驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 创建数据库连接
Connection connection = DriverManager.getConnection(url);

One is obtained through the DataSource (data source) object. In practical applications, the DataSource object will be used.

DataSource ds = new MysqlDataSource();
((MysqlDataSource) ds).setUrl("jdbc:mysql://localhost:3306/test");
((MysqlDataSource) ds).setUser("root");
((MysqlDataSource) ds).setPassword("root");
Connection connection = ds.getConnection();

The difference between the above two methods is:

  1. The Connection connection obtained by the DriverManager class cannot be reused. Every time the resource is released after use, the connection.close()physical connection is closed.
  2. DataSource provides connection pooling support. When the connection pool is initialized, a certain number of database connections will be created. These connections can be reused. Each time the database connection is used, the call to release the resource connection.close()will recycle the Conncetion connection object.

6.2 Statement Object

The Statement object mainly sends SQL statements to the database. The JDBC API mainly provides three kinds of Statement objects (Statement, PreparedStatement, CallableStatement).
insert image description here
There are two main ways to execute SQL:

  • executeQuery()After the method is executed, it returns a single result set, usually used in the selectstatement
  • executeUpdate()The method return value is an integer indicating the number of rows affected, typically used in update、 insert、 deletestatements

6.3 ResultSet object

The ResultSet object, which is called the result set, represents all the rows that meet the conditions of the SQL statement, and it provides access to the data in these rows through a set of getXXX methods.

The data in the ResultSet is arranged row by row, each row has multiple fields, and there is a record pointer. The data row pointed to by the pointer is called the current data row, and we can only operate the current data row. If we want to get a certain record, we need to use ResultSetthe next()method. If we want to get all the records in the ResultSet, we should use the while loop.

7. Notes on using JDBC

  1. Use of URLs
    insert image description here
  2. Placeholder?
    insert image description here
  3. connected to the databaseConnection
    insert image description here
  4. Close the sequence of releasing resources
    insert image description here
  5. Traversal of ResultSet objects
    insert image description here

8. Specific operations used by JDBC

8.1 Use of inserting the corresponding JDBC

Steps:

  1. Create a DateSource object (configure three aspects of URL User Password)
  2. Establish a connection to the database Connection (handle SQLException)
  3. Assemble SQL statements and use PrepareStatement objects
  4. After the assembly is complete, execute the SQL statement
  5. After execution, close and release related resources (release after creation)

Code example:

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class InsertJDBC {
    
    
    public static void main(String[] args) throws SQLException {
    
    
        // 1. 创建 DataSource 对象
        DataSource dataSource = new MysqlDataSource();
        // 需要针对dataSource 进行一些配置,以便后面能够顺利的访问到数据库服务器
        // 主要配置三方面信息: URL,User,Password 需要进行向下转型
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java20220310?characterEncoding=utf-8&useSSL=true&serverTimezone=UTC");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("0000");

        // 2. 和数据库建立连接
        // 建立连接是为了验证当前网络通信是否正常
        // 如果不正常就会抛出 SQLException 异常
        // connection 对象生命周期应该是较短的.每个请求创建一个新的 connection.
        Connection connection = dataSource.getConnection();

        // 3. 拼装 SQL 语句,用到 PrepareStatement 对象
        String sql = "insert into student values(1,'曹操')";
        PreparedStatement statement = connection.prepareStatement(sql);
        System.out.println(" statement : "+statement);

        // 4. 拼装完成之后,可以执行 SQL 了
        // insert delete update 都使用 executeUpdate 方法来执行
        // select 就使用 executeQuery 来执行
        // 返回值表示此次操作修改了多少行
        int ret = statement.executeUpdate();
        System.out.println(" ret : "+ret);

        // 5. 执行完毕后,关闭释放相关资源
        // 一定是后创建的先释放
        statement.close();
        connection.close();
    }
}

8.2 Delete the corresponding use of JDBC

Steps:

  1. Create a DataSource object (also configure three aspects of information)
  2. Create database connection Connection
  3. Assemble SQL statements and use PrepareStatement objects
  4. After the assembly is complete, execute the SQL statement
  5. After execution, close and release related resources (release after creation)

Code:


import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class DeleteJDBC {
    
    
    public static void main(String[] args) throws SQLException {
    
    
    	// 1. 创建 DataSource 对象
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java20220310?characterEncoding=utf-8&useSSL=true&serverTimezone=UTC");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("0000");
		// 2. 创建数据库连接Connection
        Connection connection = dataSource.getConnection();
		// 3. 拼装 SQL 语句,用到 PrepareStatement 对象
        String sql = "delete from student where name = ?";
        System.out.println("请输入要删除的学生姓名: ");
        Scanner sc = new Scanner(System.in);
        String name = sc.nextLine();
		// 4. 拼装完成后,执行 SQL 语句
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1,name);

        int ret = statement.executeUpdate();

        if(ret == 0) System.out.println("删除失败");
        else System.out.println("删除成功");
		// 5. 关闭释放资源
        statement.close();
        connection.close();
    }
}

8.3 Modify the use of the corresponding JDBC

Steps:

  1. Create a DataSource object (also configure three aspects of information)
  2. Create database connection Connection
  3. Assemble SQL statements and use PrepareStatement objects
  4. After the assembly is complete, execute the SQL statement
  5. After execution, close and release related resources (release after creation)

Code:

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class UpdateJDBC {
    
    
    public static void main(String[] args) throws SQLException {
    
    
    	// 1. 创建 DataSource 对象
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java20220310?characterEncoding=utf-8&useSSL=true&serverTimezone=UTC");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("0000");
		// 2. 连接数据库
        Connection connection = dataSource.getConnection();
		// 3. 拼接 SQL语句
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要修改的学生id: ");
        int id = sc.nextInt();
        System.out.println("请输入要修改的学生姓名: ");
        String name = sc.next();
        String sql = "update student set name = ? where id = ?";
        // 4. 执行 SQL 语句
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1,name);
        statement.setInt(2,id);

        int ret = statement.executeUpdate();
        if(ret == 1) System.out.println("修改成功");
        else System.out.println("修改失败");
		// 5. 关闭释放资源
        statement.close();
        connection.close();
    }
}

8.4 Find the corresponding JDBC usage

Steps:

  1. Create a DataSource object (also handles three aspects of information)
  2. Create a Connection object and establish a connection with the database
  3. Splice SQL statements with PrepareStatement
  4. Execute SQL statement
  5. iterate over the result set
  6. close release resources

Code:

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class SelectJDBC {
    
    
    public static void main(String[] args) throws SQLException {
    
    
        // 1. 创建 DataSource 对象
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java20220310?characterEncoding=utf-8&useSSL=true&serverTimezone=UTC");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("0000");
        // 2. 创建 Connection 对象,和数据库建立连接
        Connection connection = dataSource.getConnection();
        // 3. 借助 PrepareStatement 拼接 SQL 语句
        String sql = "select * from student";
        PreparedStatement statement = connection.prepareStatement(sql);
        // 4. 执行 SQL 语句
        ResultSet resultSet = statement.executeQuery();
        // 5. 遍历结果集.
        while (resultSet.next()){
    
    
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            System.out.println("id: "+id+"name: "+name);
        }
        // 6. 关闭释放资源
        resultSet.close();
        statement.close();
        connection.close();
    }
}

Guess you like

Origin blog.csdn.net/wwzzzzzzzzzzzzz/article/details/123418831