[MySQL] Initial JDBC programming


Column introduction: MySql database from entry to advanced.

Topic source: leetcode, Niuke, Jianzhi offer.

Creation goal: record the learning process of learning MySql

I hope to help others while improving myself, and make progress together with everyone and grow up with each other.

Academic qualifications represent the past, ability represents the present, and learning ability represents the future! 


Table of contents:

1. The necessary conditions for database programming

2. Java database programming JDBC

3. Working principle of JDBC

4. Use of JDBC


1. The necessary conditions for database programming

  • Programming languages: java , C , C++ , Python, etc.
  • Database: Oracle, MySQL, SQL Sever, etc.
  • Database driver package: Different databases provide different database driver packages corresponding to different programming languages, eg: MySQL provides a Java driver package mysql-connector-java, which is required to operate MySQL based on Java.

2. Java database programming JDBC

  • What is JDBC?

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

  • What are APIs?

API stands for Application Programming Interface. In layman’s terms, you have a thing, and what functions and services this thing can provide you. For example: you have a friend, and the friend plays with you, helps you, and keeps you company. This is the API provided by the friend .The same java standard library will also provide some APIs, such as: Random random number, Scanner, collection class... (a set of classes/methods), and the database ( MySQL) will also pass the API for us. With these APIs, we You can operate the database and complete various operations of adding, deleting, modifying and checking. The original intention of the database to provide API is to let us realize the client.

  • What is a client?

In actual development, SQL is rarely entered manually, and most SQL is automatically executed through code. In order to achieve this goal, it is necessary to use other languages ​​to operate the database server. Compared with implementing a database server, It is very easy to implement a database client by yourself. A set of API provided by various databases allows us to implement a client more conveniently.

  • Unification of APIs

Databases like Oracle, SQL Sever, and SQLite have their own unique APIs. This is undoubtedly bad news for grassroots programmers. Programmers must master a different set of APIs every time they learn a database. Although the APIs of each database are different, they The grammar difference is not very big, which will lead to easy confusion and bugs. At this time, if the API is unified into one set and standards are formulated, it will bring great convenience to the operation of the database. JDBC was born in the Java circle API standard, and now the JDBC API has become a part of the Java standard library. Due to the strong influence of Java itself, JDBC takes itself as the standard. At this time, various database manufacturers provide driver packages that can adapt to JDBC "(Equivalent to the specific implementation of API). At this time, as long as we have mastered this set of API, no matter which database we operate, the operation code is basically the same. JDBC shields the differences between native APIs of different databases, and uses a set of API Interface to standardize the programming operations of all databases.


3. Working principle of JDBC

JDBC unifies access methods for various relational databases. As a high-level abstraction for specific vendors to access database APIs, it mainly includes some common interface classes.

  • JDBC access to database hierarchy

 Advantages of JDBC:

  • The operation of the Java language on the database is completely oriented to abstract interface programming.
  • The development of database applications is not limited to the APIs provided by database vendors.
  • The portability of the program is greatly enhanced.

4. JDBC use:

  • Import driver compressed package 

To use JDBC, you need to use the driver package provided by the database manufacturer. This URL is convenient for testing and downloading.  Maven Repository: Search/Browse/Explore (mvnrepository.com)

After opening the URL, enter mysql to access the item with the most usage.

 Choose a version after 5.1, this article chooses 8.0.28.

 Click jar to start downloading the driver package. (.jar is similar to a compressed package in Java format), in which there are many .class files (binary bytecode files generated by compiling .java).

 

 Create a java project.

 Right-click the jdbc project, create a directory (the name can be arbitrary, here it is named lib), and copy the downloaded .jar package to lib.

Right-click and select Add as Library... (meaning to use this directory as a library) 

 

At this point, ideal can parse out the contents of the .jar package. 

 

 Then you can write code


  • Write JDBC code

1. Use JDBC to insert a record into the database.

The database and data tables need to be prepared in advance.

mysql> create database Demo;
mysql> create table student(id int , name varchar(20);

1. Create a data source, where is the description database?

DataSource is an interface API provided by JDBC, where is the description data? The specific implementation class is provided by the corresponding database driver package. MysqlDataSource is the implementation class provided in the database driver package.

DataSource dataSource = new MySqlDataSource();//向上转型

What is puzzling here is why it is necessary to transform upwards and then downwards. Is it not possible to directly use MysqlDataSource to create instance objects? Of course, but writing in this way can prevent MysqlDataSource from spreading to various places in the code (high cohesion), JDBC-oriented The database is not just MySQL, if we use other databases later, we only need this code.

//设置数据库所在位置,用户,密码. 向下转型
((MySqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/Demo?characterEnconding=utf8&useSSL=false");
((MysqlDataSource)dataSource).setUser("root");
((MysqlDataSource)dataSource).setPassword("*******");//数据库登录密码

Url=>Unique resource address symbol. It describes the only resource location on the Internet, which is a common URL in life. Although the IP address of each computer is different, it is uniformly written as 127.0.0.1 here. This is a special The IP address of , called " loopback IP ", means the host itself (equivalent to this in Javaz ). As long as your database and JDBC are on the same computer, you can use this IP address.

The Url is equivalent to the address, and the user and login password are equivalent to the key . Only when the above three points are met can the database be found.

The operation of the data source above only describes where the database is? It does not actually access it, and the "connection operation" is the real start of spreading through the network. 


2. Establish a connection with the database. (The JDBC code written is essentially a SQL client , communicating with the server through the network).

 Connection is the core concept in network communication, called " connection ". Just like going to the Civil Affairs Bureau to register for marriage, the network connection is also to find a place to record, which client and which server, the connection is established and the communication is about to begin.

 Connection connection = dataSource.getConnection();

3. Create a SQL statement to complete the insert operation.

String sql = "insert into student values(1,'张三')";

JDBC also needs to be matched with a specific object to describe the sql situation here. 

PrepareStatement preprocessing statement will preprocess the sql statement.

PreparedStatement statement = connection.prepareStatement(sql);

4. Execute SQL statement (control client to send request to server).

For addition, deletion, and modification, use executeUpdate to execute. For query, use executeQuery to execute. Execution is to send a network request to the server.

The meaning of the returned result is that this operation affected several rows.

int ret = statement.executeUpdate();

Similar to affected in sql. 

Query OK, 1 row affected (0.00 sec)

5. Disconnect from the database and release the necessary resources.

When the connection is no longer used, it is necessary to release the connection and erase the previous records.

statement.close();
connection.close();

Tips: The release order of resources is opposite to the order of creation.


The above insert operations are less modifiable and are usually written as dynamic versions.

String sql = "insert into student values("+ id + ",'" + name + "')";

However, this version is not only poor in readability, but also prone to hacker injection attacks. It is generally not recommended to use string splicing to construct sql. A more reliable way is to replace placeholders . The first? The subscript is 1, and the second A? The subscript is 2.

String sql = "insert into student values(?,?)";
PrepareStatement statement = connection.prepareStation(sql);
statement.setInt(1,id);
statement.setString(2,name);

2. Query the data in the table 

The modification and deletion operations only need to change the sql statement, and the focus is on the search operation. The search operation has an additional step of traversing the result set.

public class JDBCSelectDemo {
    public static void main(String[] args) throws SQLException {
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java106?characterEncoding=utf8&&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("111111");

        Connection connection = dataSource.getConnection();

        String sql = "select * from student";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.executeQuery();
        ResultSet resultSet = statement.executeQuery();//返回结果集
        while (resultSet.next()){
            //next 相当于移动一下光标 , 光标指向下一行 , 移动到结尾就返回false.
            //获取什么类型就使用什么类型的方法.
            //这里的参数 , 就是数据库表的列名
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            System.out.println(id + ": " + name);
        }

        //释放资源
        resultSet.close();
        statement.close();
        connection.close();
    }
}

The meaning of JDBC:

A few short commands on the command line require a long code in JDBC. Is this tasteless? In fact, the code is written to let the Java program quickly and repeatedly execute some fixed sql statements. sql statement execution The number of times is small, we can do it manually, but what if it is executed 10,000 times? Obviously it cannot be done. Most of the code in JDBC is fixed, so there are some libraries and frameworks that further encapsulate JDBC, and then It is more convenient for us to use. eg: Mybatis, JPA... But JDBC learning still has great significance. The framework is always changing, but JDBC is constant. If some frameworks do not meet our needs, they can be based on JDBC Make frame customizations.

Guess you like

Origin blog.csdn.net/liu_xuixui/article/details/128013980