JDBC programming in Java—connecting to Mysql database

Table of contents

1. Java database programming: JDBC

2. JDBC working principle

3. JDBC use

4. Summary of JDBC usage steps

 5. JDBC common interfaces and classes

5.1 JDBC API

5.2 Database connection Connection

5.3 Statement object

5.4 ResultSet object


1. Java database programming: JDBC

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

2. JDBCWorking Principle

        ​​​​JDBC provides a unified access method for a variety of relational databases. As a high-level abstraction of a specific vendor's database access API, it mainly includes some common interface classes.
 
JDBC access database hierarchy:
 
03ec87ca8ed1468ba894a0b4ef601426.png
 
JDBC advantages:
 
  • Java language access database operations are completely oriented to abstract interface programming
  • Developing database applications does not need to be limited to the API of a specific database vendor.
  • Program portability is greatly enhanced

3. JDBCUse

  • Prepare the database driver package and add it to the project's dependencies:

       Create the folder lib in the project and copy the dependency package mysql-connector-java-5.1.47.jar to lib. Then configure the jar package into the dependencies of this project: right-click the project Open Module Settings, in Modules, click the project, configure Dependencies, click +, JARS or Directories, configure the lib folder into the dependencies, indicating the folder The jar packages under are introduced as dependencies.

  •  Establish database connection

    The URL parameter format of MySQL data connection is as follows:
jdbc:mysql://server address:port/database name?Parameter name=parameter value

// 加载JDBC驱动程序:反射,这样调用初始化com.mysql.jdbc.Driver类,即将该类加载到JVM方法
区,并执行该类的静态方法块、静态属性。
Class.forName("com.mysql.jdbc.Driver");

// 创建数据库连接
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?
user=root&password=root&useUnicode=true&characterEncoding=UTF-8");
  • Create an operation command (Statement)
//3.构造一个Sql
 String sql =" insert into stu(id,name,age) values(1,zhang,3)";

//需要把 Sql语句转化为对象
 PreparedStatement statement = connection.prepareStatement(sql);
  • Use action commands to execute SQL
// 查询操作
preparedStatement.executeQuery();

// 新增、修改、删除操作
preparedStatement.executeUpdate();
  • Process the result setResultSet.
    //接受结果集合         
     ResultSet resultSet = statement.executeQuery();
        //结果集遍历
        while (resultSet.next()){
            //移动光标
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            int age = resultSet.getInt("age");
            System.out.println(id+" "+name+" "+age+" ");
        }
  • Release resources
try {
    if(resultSet != null){
        resultSet.close();
   }
    if(preparedStatement != null){
        preparedStatement.close();
   }
    if(connection != null){
        connection.close();
   }
} catch (SQLException e) {
    e.printStackTrace();
    throw new RuntimeException("数据库错误");
}

4. JDBC Summary of usage steps

1. Create a database connection Connection
2. Create an operation command Statement
3. Use operation commands to execute SQL
4. Process the result set ResultSet
5. Release resources

 5. JDBCCommonly used Japanese class

5.1 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. Therefore, mastering the Java JDBC API (located under the java.sql package) can master Java database programming.

5.2 ConnectionConnection

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 DriverManager (driver management class):
    // 加载JDBC驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 创建数据库连接
Connection connection = DriverManager.getConnection(url);
  • One is to obtain it through the DataSource (data source) object. Will be used in actual applicationsDataSourceObject
 DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://localhost:3306/db1?serverTimezone=UTC");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");

The difference between the above two methods is:

   1. The Connection obtained by the DriverManager class cannot be reused. Every time the resource is released after use, the physical connection is closed through connection.close().

   2. DataSource provides connection pool support. The connection pool will create a certain number of database connections during initialization. These connections can be reused. Every time the database connection is used and resources are released, calling connection.close() will recycle the Conncetion connection object.

 

5.3 StatementImage

The Statement object mainly sends SQL statements to the database. There are three main types of Statement objects provided in the JDBC API:

 4aec17b72233456a91d6b358f0a6fc8e.png

There are two main ways to execute SQL:
  • The executeQuery() method returns a single result set after execution, usually used in select statements.
  • The return value of the executeUpdate() method is an integer indicating the number of affected rows, usually used for update, insert, and delete statements.

5.4 ResultSetResult

        The ResultSet object is called the result set, which represents all 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 a record pointer. The data row pointed to by the pointer is called the current data row. We can only operate on the current data row. If we want to get a certain record, we must use the next() method of ResultSet. If we want to get all the records in the ResultSet, we should use a while loop.

6. Sample code 

import com.mysql.cj.jdbc.MysqlDataSource;

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

public class TestJDBC {
    public static void main(String[] args) throws SQLException {
        // MysqlDataSource dataSource = new MysqlDataSource();
        //dataSource.setUrl();
        //1. 创建数据源,即获取数据库的位置
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://localhost:3306/db1?serverTimezone=UTC");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");

        // 2 .和数据库服务器建立连接
        Connection connection = dataSource.getConnection();

        //3.构造一个Sql
        String sql =" insert into stu(id,name,age) values(?,?,?)";
      //  String sql =" insert into stu(id,name,age) values(1,zhang,3)";
        //需要把 Sql语句转化为对象
        PreparedStatement statement = connection.prepareStatement(sql);

        statement.setInt(1,66);
        statement.setString(2,"a");
        statement.setInt(3,7);
        //4.构造好的sql 发送给服务器;
       int n = statement.executeUpdate();
        System.out.println("n:"+ n);

        //5.最后一步 释放资源
        statement.close();
        connection.close();
    }
}

 Conclusion:This ends the JDBC-related sharing. I hope it will be helpful to everyone’s study. If you have any questions or different opinions, please feel free to leave them in the comment area. Leave a message, ganxiezhich~~~

 

 

Guess you like

Origin blog.csdn.net/qq_61576108/article/details/134417809