当前位置:网站首页>JDBC read this article is enough

JDBC read this article is enough

2022-07-06 14:19:00 Want to enter a big factory

List of articles


Preface

To learn the Mysql After the database , I spent two days studying JDBC Use , Here is a summary of the author's comments on jdbc The understanding of the ( notes : All the code in this article is for Mysql Database coding )


Tips : The following is the main body of this article , The following cases can be used for reference

One 、JDBC What is it? ?

JDBC yes SUN A set of interfaces developed by the company , Interfaces have callers and implementers , Interface oriented call 、 Interface oriented writing implementation classes 、 This is all interface oriented programming .

Two 、JDBC Schematic diagram

JDBC API It's a series of interfaces , It unifies and standardizes the connection between application and database , perform SQL sentence , And get the return results and other operations , Related classes and interfaces are in java.sql and javax.sql In bag

3、 ... and 、JDBC How to use

JDBC Import mysql Driver file

(1) stay Mysql Download the corresponding driver on the official website jar package , According to what you use mysql Version select the appropriate version to download , If it is Mac Ben , choice tar.gz File download , If it is win System , choice zip File download , Finally, decompress it

(2) stay IEDA Import driver file in

And then choose  

That 's it. Right Mysql Import the database driver file

Four 、JDBC Coding steps

1. Registration drive , Get the connection

There are five ways to create a database connection , Let me give you a brief introduction

Driver Interface method :

Connectionconnect(String url, Properties info)

Try to connect the database to the given URL

Back to connect Objects are objects that connect data

The first way :

public void connect01() throws SQLException {

        // Registration drive 
        Driver driver = new Driver();
        //jdbc:mysql:// It's a stipulated agreement ,localhost:3306 Representing this machine   And listening ports ,xyx_db02 Means to connect to xyx_db02 This table 
        String url = "jdbc:mysql://localhost:3306/xyx_db02";
        // take   user name   and   password   Put in  Properties  In the object 
        Properties properties = new Properties();
        properties.setProperty("user","root"); // user  ,properties(key,value) key It's prescribed  "user"
        properties.setProperty("password","123"); // password 
        Connection connect = driver.connect(url, properties); // Back to a connection 
        System.out.println(connect);
    }

The second way : adopt java Reflection mechanism loading Driver class

public void connect02() throws Exception {
       // Use reflection to load Driver class  , Dynamic loading , More flexible , Reduce dependency 
        Class<?> cls = Class.forName("com.mysql.jdbc.Driver");
       Driver driver = (Driver) cls.newInstance();
        String url = "jdbc:mysql://localhost:3306/xyx_db02";
        // take   user name   and   password   Put in  Properties  In the object 
        Properties properties = new Properties();
        properties.setProperty("user","root"); // user  ,properties(key,value) key It's prescribed  "user"
        properties.setProperty("password","123"); // password 
        Connection connect = driver.connect(url, properties); // Back to a connection 
        System.out.println(" Mode two "+connect);

    }

The third way : adopt DriverManager Class registerDriver Methods the incoming driver Object completes the connection to the database

static ConnectiongetConnection(String url, String user, String password)

Try to build a database with a given one URL The connection of

public void connect03() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {

       // Use reflection to load Driver
        Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
       Driver driver = (Driver) aClass.newInstance();

       // establish url  and  user  and password
        String url = "jdbc:mysql://localhost:3306/xyx_db02";
        String user = "root";
        String password = "xuyuxuan0724";

        DriverManager.registerDriver(driver); // register Driver drive 

        Connection connection = DriverManager.getConnection(url, user, password);

        System.out.println(" The third way = " + connection);
    }

The fourth way :Class.forName() Method , Automatically complete the registration drive

public  void  connect4() throws ClassNotFoundException, SQLException {
       //com.mysql.jdbc.Driver

       // Use reflection to load Driver class 
        Class.forName("com.mysql.jdbc.Driver");

        // establish url  and  user  and password
        String url = "jdbc:mysql://localhost:3306/xyx_db02";
        String user = "root";
        String password = "xuyuxuan0724";
        Connection connection = DriverManager.getConnection(url, user, password);
        System.out.println(" The fourth way  = " +connection);
    }

Two points need to be explained here :

1.Mysql drive 5.1.6 Then you don't need Class.forName("com.mysql.jdbc.Driver");

2. from jdk1.5 Used jdbc4, No need to show calls Class.forName() Registration drive , Instead, the driver is called automatically jar It's a bag META-INF\services\java.sql.Driver Register the class name in the text

The fifth way : Write to configuration file , Give Way mysql More flexible connection , Reduce code redundancy

 

 public void connect05() throws IOException, ClassNotFoundException, SQLException {

       // adopt Properties Object to get the information of the relevant configuration file 
        Properties properties = new Properties();
        properties.load( new FileInputStream("src//mysql.Properties"));
        // Get the relevant values 
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String driver = properties.getProperty("driver");
        String url = properties.getProperty("url");
        Class.forName(driver);

        Connection connection = DriverManager.getConnection(url, user, password);
        System.out.println(" Methods five  " +connection);
    }

DriverManager Do not call registerDriver() Methods the incoming driver What is it for? ?

Because when the class is loaded ,Driver Class underlying static This method has been called in the code block , It is an automatic registration driver

Here attached Driver Class :

public class Driver extends NonRegisteringDriver implements java.sql.Driver{
    
    static {
        try{
            java.sql.DriverManager.registerDriver(new Driver());
        } catch(SQLException E) {
            throw new RuntomeExceptione("Can't register driver!");
        }
    }

Okay , I believe you see here , Yes JDBC We have a general understanding of the way to connect to the database , Here we go to the next step

2. organization SQL sentence

        String sql = "Update  actor set name = ' Stephen Chow ' ";
        // Used to operate  sql sentence 
        Statement statement = connect.createStatement(); //
        int rows = statement.executeUpdate(sql); // If it is  dml sentence   What is returned is the number of affected rows 
        System.out.println(rows >0 ?" success ":" Failure "); // 1

Code tested , The return is success ;

Here's a question ,Statement Classes are not allowed in development , Because it has a SQL Injection problem , Let's take a look at a typical SQL Injection problem :

If we use select sentence , Here we will judge where hinder sql sentence , The data we originally wanted to query name ='tom',pwd='123', And the one above sql Statement is equivalent to writing a universal conditional statement ,name='1' perhaps pwd = ' perhaps '1=1', Obviously, we can query the data we want , It is said that in 2000 About years ago , because sql The injection problem has caused heavy losses to many enterprises , The latter problem was solved

Let's introduce Statement class

Statement class

Basic introduction :

1. For execution static Sql Statement and return its generated result

2. After the connection is established , Need to access the database , Execute naming or SQL sentence , Can pass Statement( There is SQL Injection problem )PrepardStatement( Preprocessing ) CallableStatement( stored procedure )

3.Statement Object to perform SQL sentence , There is SQL Injection risk

4.SQL Injection is the use of some systems that do not adequately check the user input data , And inject illegal pairs into user input data SQL A statement or command , Malicious attack database

5. Guard against SQL Inject , Just use PreparedStatement( from Statement Extended ), replace Statement That's all right.

Talk about select sentence , Let's introduce ResultSet class

ResultSet class

A data table that represents a database result set , Typically generated by executing statements that query the database .

ResultSet Object keeps a cursor pointing to its current data row .  first , The cursor is before the first line . next Method to move the cursor to the next line , And because in ResultSet Returns... When there are no more rows in the object false , So it can be found in while Loop to traverse the result set .

Let's take a look ResultSet Bottom

rows All right , It's a ArrayList Array ,internalRowDate It's an array of objects , Each object array contains rows of data , for instance 0 The corresponding is 49 yes id by 1 Of ASCll code ,1 Corresponding name Medium ‘ Stephen Chow ‘,UTF-8 Each Chinese character occupies three bytes , So there are nine ascll Code and so on

Because it's just testing , We've built the watch

mysql> select * from actor;
+----+-----------+-----+---------------------+-------+
| id | name      | sex     | borndate            | phone |
+----+-----------+-----+---------------------+-------+
|  1 |  Stephen Chow      |  male       | 1970-11-11 00:00:00 | 110   |
|  3 |  Lau Andy      |  male       | 1970-12-12 00:00:00 | 110   |
|  4 |  headmaster      |  male       | 1969-01-01 00:00:00 | 1231  |
+----+-----------+-----+---------------------+-------+

        //1. Registration drive 
        Class.forName(driver);
        //2. Get connected 
        Connection connection = DriverManager.getConnection(url, user, password);
        //3. obtain Statement
        Statement statement = connection.createStatement();
        //4. organization sql sentence 
        String sql = "select id,name,sex,borndate from actor";
        // Perform a given sql sentence , This statement returns a single  ResultSet object 
        ResultSet resultSet = statement.executeQuery(sql);

 while (resultSet.next()){ // Will move the cursor backwards , If there is no more line , Will return false
            int id =  resultSet.getInt(1);// Get the data in the first column of this row 
            String name = resultSet.getString(2); // Get the data in the second column of this row 
            String sex = resultSet.getString(3);// Get the data in the third column of this row 
            Date date = resultSet.getDate(4);
            System.out.println(id+"\t"+name+"\t"+sex+"\t"+date);

        }

The return result is :

3. close resource

stay JDBC In the coding process , We created resultSet,statement,connection And so on , These resources must be closed after use , Follow the principle of "from inside to outside" in the process of closing , Because such closing operations are used in the operations of adding, deleting, modifying and querying

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

Attached below is information about select The complete code of the query statement :                                                                                                                                                

import java.io.FileInputStream;
import java.sql.*;
import java.util.Properties;

@SuppressWarnings({"all"})
public class ResultSet_ {
    public static void main(String[] args) throws Exception {
        // adopt Properties Object to get the information of the relevant configuration file 
        Properties properties = new Properties();
        properties.load( new FileInputStream("src//mysql.Properties"));
        // Get the relevant values 
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String driver = properties.getProperty("driver");
        String url = properties.getProperty("url");

        //1. Registration drive 
       // Class.forName(driver);
        //2. Get connected 
        Connection connection = DriverManager.getConnection(url, user, password);
        //3. obtain Statement
        Statement statement = connection.createStatement();
        //4. organization sql sentence 
        String sql = "select id,name,sex,borndate from actor";
        // Perform a given sql sentence , This statement returns a single  ResultSet object 
        ResultSet resultSet = statement.executeQuery(sql);

        //5. Use while Take out the data 
        /*
            mysql> select * from actor;
            +----+-----------+-----+---------------------+-------+
            | id | name      | sex     | borndate            | phone |
            +----+-----------+-----+---------------------+-------+
            |  1 |  Stephen Chow      |  male       | 1970-11-11 00:00:00 | 110   |
            |  3 |  Lau Andy      |  male       | 1970-12-12 00:00:00 | 110   |
            |  4 |  headmaster      |  male       | 1969-01-01 00:00:00 | 1231  |
            +----+-----------+-----+---------------------+-------+

         */
        while (resultSet.next()){ // Will move the cursor backwards , If there is no more line , Will return false
            int id =  resultSet.getInt(1);// Get the data in the first column of this row 
            String name = resultSet.getString(2); // Get the data in the second column of this row 
            String sex = resultSet.getString(3);// Get the data in the third column of this row 
            Date date = resultSet.getDate(4);
            System.out.println(id+"\t"+name+"\t"+sex+"\t"+date);

        }

        //6. close resource 
        resultSet.close();
        statement.close();
        connection.close();

    }
}

JDBC That's all for programming , If you have mastered all , And business , Gain self increase , You can learn about connection pools by yourself  

原网站

版权声明
本文为[Want to enter a big factory]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060918254808.html