Happy to take you to learn the MySQL database at the end of the festival

Please add image description

JDBC programming in Java

When developing various databases, MySQL, Oracle, and SQL Server, they will provide a set of programming interfaces (APIs).
API ~~ Application Programming Interface ~~ Application Programming Interface
is a very common concept in the computer field.
Let me give you a Software, what can you do to it (from the code level)
based on the functions it provides, you can write some other code (so abstract!)

example:

image-20230910194247740

What is the difference between function => C language and method => Java??
No difference~~ Many times, these two words are used interchangeably~~ Strictly speaking, there is a difference, but not much.
Essentially, it is a piece of code that can be executed and reused~

The origin of JDBC

The reason why the APIs provided by MySQL, Oracle, and SQL Server are different
: Where there are people, there are rivers and lakes. MySQL, Oracle, and SQL Server were developed by three different teams, and three different APIs appeared. As a result, as programmers, we have to learn multiple APIs, and the learning cost becomes high.
At this time, a very important boss (Java) came to adjust, and
Java proposed a set of API interfaces. Standard requires other manufacturers to implement APIs according to this standard. Of course, other manufacturers' native APIs do not need to be significantly modified. It is just a matter of writing some code, packaging them, and packaging them to comply with the set of API standards proposed by Java => From now on, Java programmers only need to learn this set of API styles~~ No matter what database is changed to, how the underlying things change, the upper-layer things, that is, the code written by the programmers, are the same => Reduced Programmer’s Learning Burden
The name of this set of APIs proposed by java is called JDBC.
JDBC provides a standard API for Java developers to operate databases and can provide unified access to multiple relational databases.

image-20230910215228119

If Java programmers want to develop databases, they need to import the driver package corresponding to the database in their own projects before writing code.
We often see hardware drivers. Hardware drivers allow the operating system to recognize new hardware devices. Database drivers allow JDBC to recognize the API of the database.

Where does the driver package come from?


~~ Obtain the official website of 1.mysql provided by the database manufacturer
~~ The next step => After mysql was acquired by Oracle, the official website was also merged and became a sub-page of Oracle’s official website, and Oracle’s official website is a very difficult to use official website :
(1) It’s not easy to find things at all. I don’t know where they are hidden in the corner.
(2) Login authentication is required at every turn. The requirements for the login account and password are high, and it is troublesome to retrieve the password if you forget it.
2. github => Open source projects generally have code on it, which can be found on it.
3. Maven's central warehouse
maven => Equivalent to the app store on your mobile phone.
Central warehouse => A server that hosts various software packages.
Through the app store, you can access software packages and download them
image-20230910232444068

image-20230910233329604

image-20230911000202934

Jar package => Java is a typical way to publish programs.
Java is compiled into .class files through java source files, and jvm interprets and executes the .class. Each java corresponds to a .class.
What if there are a lot of java in the code?
Put a lot of them .class is packed into a compressed package (similar to .rar.zip). The compressed package here is .jar ~~ A .jar contains many .class files~~ Copy the jar package to the other party, and the other party can directly Use jvm to run.
Here, the jar package of the mysql driver package is not a jar package that can be run separately. You can import it into our project and then call the methods and classes in it for programming!!!

It’s not that easy for hackers to invade your computer. The anti-virus software that comes with Windows is already very powerful => Windows Security Center.
Of course, if you really want to visit some unknown websites, it is recommended to install a virtual machine software on your computer and put it in the virtual machine. Install a virtual operating system and access it through the virtual host constructed in the virtual machine software. Even if a hacker invades, it will be your virtual machine~~ At that time, just delete the virtual machine and create a new one~~ Tips

How to import database driver package
  1. Create a Java project in IDEA

  2. Create a directory (New Directory)lib ~~ in the project, copy the jar package and paste it into the lib directory

  3. Right-click on lib and select Add as library => The purpose is to mark this lib directory as a project library, so that idea can identify the jar package in this directory and call the classes in it to write code. Note: Each time a project is
    created Everyone has to do this

  4. Writing JDBC code~~ Taking insertion as an example,
    create a JDBCInsert.java file in src

    public class JDBCInsert {
          
          
        public static void main(String[] args) throws SQLException {
          
          
            //JDBC 需要通过一下步骤来完成开发
    
            //1. 创建并初始化一个数据源
            DataSource dataSource = new MysqlDataSource();//向上转型~~父类引用指向子类对象
            ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/fly?characterEncoding=utf8&useSSL=false");//设置URL
            ((MysqlDataSource) dataSource).setUser("root");//设置用户名 ~~ 用户名都是root(默认就是root)
            ((MysqlDataSource) dataSource).setPassword("0213");//设置密码 ~~ 安装数据库的时候密码是什么就写什么
            //这几个东西都设置进去,才能够访问数据库服务器 
            //~~ 并且这个代码只是设置数据源,描述数据库服务器在哪
            //~~还没真正和数据库服务器连接呢!!
    
            /*(注意,上述代码,不使用向上转型,向下转型,就直来直去的写,也可以!!没有任何问题)(C++的风格),
            之所以向上面这么写,完全是因为Java这个圈子里,流行这么写
            代码如下:
            MysqlDataSource dataSource = new MysqlDataSource();
            dataSource.setURL();*/
    
            //2.和数据库服务器建立连接
            Connection connection = dataSource.getConnection();
    
            //3.构造SQL语句
            String sql = "insert into student value(1, 'fly')";
            PreparedStatement statement = connection.prepareStatement(sql);
    
    
            //4.执行SQL语句
            int ret = statement.executeUpdate();
            System.out.println("ret = " + ret);
            //把sql语句(预编译过的)发送给数据库服务器,由服务器做出响应
    
            //5.释放必要的资源
            statement.close();
            connection.close();
        }
    }
    
    1. Run the code, check the running results, and check it on the mysql client to verify whether it is successful again.
    Partial understanding of the above code

    Data source => Where the data comes from, describe where the database server is~~ DataSource , an interface, an API provided to us by JDBC

    setURL : This method is available in subclasses but not in the parent class. If you want to use it, you need to convert the parent class reference back to the subclass reference~~ (downward transformation)

    URL : A common term in computers, a unique resource locator~~ describes the location of a resource on the network~~ The format is very unique!!

    jdbc:mysql://127.0.0.1:3306/fly?characterEncoding=utf8&useSSL=false
    jdbc => Fixed
    mysql => It depends on what database you are using

    IP address 127.0.0.1 => mysql database is a program with a "client server" structure. The client and server communicate through the network~~ The location of the host on the network is determined by the IP address~~ 127.0.0.1 It's called loopback IP, which represents your own current host, because our database client (the jdbc code we write now) and database server (the service that previously stored data) are on the same host~~ Of course, the client and server are on the same host On different hosts, the IP must be written separately.

    3306 => Port number. The port is used to distinguish applications. The default port of the current database server is 3306. fly
    = > Created database name~~ create database database name; The parameter after
    ? indicates the parameter => characterEncoding=utf8 ~~ The character set uses utf. -8, useSSL=false ~~ SSL is an encryption protocol, false here means no encryption

    dataSource.getConnection();
    Checked exceptions must be handled explicitly. Unchecked exceptions are fine if you don’t explicitly handle them.
    If you have a runny nose, sneezing, or coughing before the COVID-19 outbreak, it is an exception, but it is not necessary. Special treatment, you will be fine with your own immunity in a few days~~ Unexamined Abnormality
    If you have a fever during the COVID-19 period, get a nucleic acid test as soon as possible, and you must be isolated immediately~~ Unexamined Abnormality

    Use PreparedStatement to precompile this SQL string in advance.
    If the request is a SQL string, the server can handle it. The server needs to parse the SQL, understand the meaning here and execute it
    ~~ If tens of thousands of clients are sending this requests, the pressure on the server will be greater!!
    ~~ Let the client pre-compile the SQL, the work done by the server will be simpler, and the pressure will be much less. For example, in a school cafeteria, students are required to finish their meals and themselves Send plates to recycling

    executeUpdate => returns int indicating the number of rows affected

    Even if we use code to operate the database, we still rely on sqI statements! It's just that the various syntaxes of previous sql are still valid
    if we use code to construct sql !

    The above code looks cumbersome, but in fact it is very simple~~
    The code here will feel very cumbersome when you first come into contact with it. It involves many new classes, new methods, new concepts and new parameters...
    but it will be easy to write it a few times. I found that the code here is a fixed routine.
    Because of this, in actual development, some frameworks will be used to simplify the database operation code~~ This is the case with frameworks like MyBatis~~
    Merely knowing the framework is not enough, you must also know the operations behind the framework , have enough understanding of the native JDBC.
    The framework is constantly changing, but JDBC remains unchanged!!! Are
    programmers just eating their youth? Because new technologies are emerging in an endless stream
    ~~ The last wave is better than the last wave~~ There are only so many By mastering these unchanging things, you can adapt to the ever-changing situation with the same things.

Love Tips

~~ When saying good night to a girl, don’t say good night, but say the pinyin wanan.
The reason for doing this is wanan => I love you, love you
and learned that there are no brothers, how romantic is this!!! (*^▽^ *)

Note: There are some tidbits in this article that need to be improved!!!

Guess you like

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