I happily take you to learn the MySQL database, part two

e2c6a1f8f6330f3e6a2948ca3ef7f429

A true warrior is one who still loves life after seeing the truth of life clearly. —— Romain Rolland

Basic work of JDBC programming

Preparation work:
1. Download the mysql driver package~~ maven central warehouse
2. Import into the project and copy it to the project directory, marked as library

Write code:
1. Create a data source (describe the location of the database server)
2. Establish a connection
3. Construct an SQL statement
4. Execute the SQL statement
5. Release resources

DataSource => Connection => PreparedStatement
DataSource ~~ describes the data source
Connection ~~ describes the connection, the connection is established by the data source
PreparedStatement ~~ prepared statement

Dynamic data insertion operation

code show as below:

public class JDBCInsert2 {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        //JDBC 需要通过一下步骤来完成开发

        //1. 创建并初始化一个数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/fly?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("0213");


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

        //3. 从控制台读取用户的输入内容
        System.out.println("请输入学生姓名: ");
        String name = scanner.next();
        System.out.println("请输入学号: ");
        int id = scanner.nextInt();
        //4. 构造SQL语句
        //String sql = "insert into student value(" + id + ",'" + name + "' )";
        // => 这样写容易被 sql注入 ~~ 网络安全中一种老牌的攻击方式

        //更好的写法,借助这个PreparedStatement的拼装功能来实现~~
        String sql = "insert into student value(?, ?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        //把占位符替换成指定的值
        statement.setInt(1, id);
        statement.setString(2, name);
        //这个打印需要加到数据之后
        System.out.println(statement);

        //4. 执行SQL语句
        int ret = statement.executeUpdate();
        System.out.println("ret = " + ret);


        //5. 释放必要的资源
        statement.close();
        connection.close();
    }
}
Why release resources

When the database client and server communicate, certain system resources are consumed, including but not limited to, CPU, memory, hard disk, bandwidth... The client is just that. Take the server as an example, it needs to be processed at the same time
. There are many clients~~ Providing services to one client requires consuming certain resources...give it ten, or give it a hundred??? How can we make
better use of these resources? => The client should use it sparingly ( Release it quickly when not in use)

The order in which resources are released

Whoever creates it last will release it first!!
In the code, what is created last is the statement => statement is released first, what
is created first is the connection => release after connection

How do you understand it???
There is an old saying, "If you don't go out through the front door, you won't be able to step out the second door." => The layout of the courtyard is as follows
image-20230912182939717

The JDBC we currently use is written using DataSource
. There is also another way to write DriverManager , which loads the classes in the driver package through reflection, and further performs subsequent operations~~

image-20230912222308339

Not recommended for use due to:

  • Reflection is a special method in Java development!!
    Using reflection will hurt the enemy a thousand times, but you will lose eight hundred~~ Do not use it lightly unless you have to!!!
    The readability of the reflected code is very poor, and it is difficult for the compiler to correct the code. It is very easy to produce runtime abnormalities when performing inspections
    ~~ similar to doctors using the analgesic drug Meperidine

  • 2.DataSource has a built-in database connection pool. It can reuse connections and improve the efficiency of connecting to the server.

Pool computer is a very important and widely used term

How to understand the concept of pool

Note: I would like to declare that the following example is written by the blogger for your understanding and has nothing to do with the blogger himself.

Suppose there is a girl who is good-looking and talented, so many people are pursuing her,
but she can only date one suitor at a time.
At this time, the girl is tired of dating suitor A and wants to change to another. It would be unrealistic for her boyfriend to break up with A right away
~~ So, she had to hold a magnifying glass against her boyfriend to see what he did wrong. If he did something wrong, she
would deliberately make a fuss out of it. Go online, get slapped with a hat, and get a beating from the feminist. If this doesn't work once, repeat it several times.
~~ My boyfriend loses patience with him. I really can't stand it anymore, so I break up with him, and it's a matter of course.

So, after the girl broke up with her pursuer A, she started dating her pursuer B, and started to develop a relationship with him. She first sent them on WeChat,
QQ, etc., and then chatted for a while. After they got to know each other a little bit, they started to develop a relationship. Went to class together,
had meals together, went out to play together... In the end, the two of them got together.

However, it takes a lot of time and energy (cost) for a girl to break up with suitor A and get together with suitor B. She even gets
tired of dating suitor B and wants to date suitor C again. The suitor C is tired of dating, and wants to date the most seeking D again
... (30,000 words are omitted below!!!)

The question is, how can a girl improve the efficiency of changing boyfriends?
The method is very simple, cultivate relationships with suitors B, C, D... in advance~~
While dating boyfriend A, don’t forget to have a relationship with the suitor. They are having an affair
~~ Now that I am tired of dating A, the day after I break up with A, B can take over. After all, the relationship has been cultivated in advance, and the groundwork is in place, making it easy to achieve a seamless connection... I am tired of dating B, You can also change it to C... When you get tired of dating C, you can also change it to D... ~~ The girl can change it at any time
~~ At this time, B, C, D... can all be called the girl's spare tire
~~ They are girls’ backup pool.

Pools are essentially "pre-application for resources"

Although it is said that it is not needed yet, you can apply for it first and use it at any time later. You can take it from the pool at any time and put it back into the pool when you are no longer using it~~ You can take it from the pool
whenever you want to use it, rather than having to start from the beginning when you want to use it. It’s much faster to apply for resources
~~ A performance that improves efficiency

Alas! "Some people are telling jokes, while others are looking in the mirror."


Implement query operations

Note: The returned result of the query is not a simple int, but a ResultSet object~~ The result set
code is as follows:

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

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

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: fly(逐梦者)
 * Date: 2023-09-12
 * Time: 23:25
 */
public class JDBCSelect {
    
    
    public static void main(String[] args) throws SQLException {
    
    
        //1.创建并初始化数据库
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/fly?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("0213");

        //2.建立连接
        Connection connection = dataSource.getConnection();
        //3.构造SQL
        String sql = "select * from student";
        PreparedStatement statement = connection.prepareStatement(sql);
        //4.执行SQL
        ResultSet resultSet = statement.executeQuery();
        //5.遍历结果集合
        while (resultSet.next()) {
    
    
            //把 resultSet想象成一个表格.同时表格这里有个光标,初始情况下光标指向表最上面
            //每次调用 next,光标往下走一行
            //当光标指向某一行的时候,就可以通过 getXXX来获取到当前这行里的数据
            /*getXXX是取出这一行的指定列的值
            ~~使用的方法要和列的类型匹配
            ~~参数可以是"第几列"下标也可以是列名~(推荐)*/
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            System.out.println("id = " + id + ", name = " + name);

            //当光标已经把整个表都遍历完了,next就会返回false了
        }

        //6.释放资源
        resultSet.close();
        statement.close();
        connection.close();
    }
}
What will it be like to actually work in the future?

It is definitely much harder than going to school now.
If you think going to school is hard now, I’m sorry, but after you go to work, it will be ten times harder than going to school.
Although graduate school is also hard, the hardship of going to work is far more difficult than going to graduate school~~I strongly recommend you to take the postgraduate entrance examination!!!
Reasons:
(1) It is also very simple. When I go to school, there is no pressure and it is very relaxed~~
(2) When I go to work, there will be a lot of pressure, pressure at work, pressure in life, pressure in all aspects
(3 ) You are not interested in the content of your work at all (normal) ~~ 90% of people are not interested in work
~~ Even if you are very interested in something, if you are asked to do it as work, you will soon lose interest
. Most people love to play games, but if you become a professional player one day, you will only be able to play
this one hero for more than ten hours a day, and play it dozens of times. Even if you are interested, you will be able to do this day and night. If you play, you won't be interested either

From now on, I only have one goal in going to work, money. I am not qualified to talk about my interests as a worker.

For a programmer, a day's work is calculated as 10 hours~~ The time spent writing code is only 2-3 hours. The
main work:
1. Debugging bugs ~~ Main theme
2. PK with various people (including but not limited to, and products Manager, and testing, and operation and maintenance, and the boss...)
3. Develop product requirements~~ Write code
4. System optimization (development + testing + design + other aspects) ~~ Usually experienced and old programmers accessible

Never look forward to "going to work"

When you were growing up, people around you rarely told you the truth. They just painted a picture for you.

Guess you like

Origin blog.csdn.net/m0_73740682/article/details/132843359