当前位置:网站首页>[JDBC from introduction to actual combat] JDBC basic customs clearance tutorial (comprehensive summary part I)

[JDBC from introduction to actual combat] JDBC basic customs clearance tutorial (comprehensive summary part I)

2022-06-21 06:28:00 Xiaohuang Xiaohuang is no longer confused

Personal home page : Huang Xiaohuang's blog home page
Stand by me : give the thumbs-up Collection Focus on
Maxim : Only one step at a time can we accept the so-called luck

This article is from the column :JDBC From introduction to practice
Welcome to the support subscription column ️
 Insert picture description here


1 JDBC summary

brief introduction :

  • JDBC by Access to different databases A unified interface is provided , Many details are shielded for users ;
  • Java Programmers use JDBC, Sure Connect any provided JDBC Driver database system , Thus, various operations on the database can be completed .

JDBC Schematic diagram :
 Insert picture description here explain : JDBC In the final analysis, it is to enable developers to pass Java The program accesses various supported database systems . However , The vendors of each database may be different , Oracle, for example 、 Microsoft … … Because we do not know the underlying structure of the database system of each manufacturer , And if you operate on different databases , The methods we use are not uniform , This is not conducive to program management . Just imagine , If you are Java Vendor developers , It's not easy to lose my hair and finish editing Mysql Code for , however Mysql Version iteration upgrades … … You have to rewrite the code , To support higher version databases !
  In order to solve the above problems , Sure from Java Program companies develop a series of specifications , Provide some interfaces for database manufacturers to implement . Supported database vendors can implement corresponding interfaces , bring Java Programs can access 、 Operating the database .


2 JDBC Quick start

2.1 JDBC Programming steps

  1. Registration drive - load Driver class ;
  2. Get the connection - obtain Connection;
  3. Perform the operations of adding, deleting, modifying and querying - send out SQL to mysql perform ;
  4. Release resources - Close the relevant connection

2.2 JDBC First program of

So let's go through JDBC Counter table student Add , Delete and modify operations , The following is the code for creating the table structure :

CREATE DATABASE mysqlforjdbctest;
USE mysqlforjdbctest;
CREATE TABLE student
(                                             --  Student list 
    id       INT PRIMARY KEY AUTO_INCREMENT,  --  Student number 
    name     VARCHAR(20) NOT NULL DEFAULT '', --  full name 
    sex      CHAR(1)     NOT NULL DEFAULT '', --  Gender 
    birthday DATETIME,                        --  Birthday 
    phone    VARCHAR(12)                      --  cell-phone number 
);

then , Let's open it first idea Prepare for operation , take mysql The corresponding connection driver is imported into the project directory , See the first section of the blogger's article for details :
How to use JDBC visit Mysql database ?

JDBCtest01 Code :

For url Some notes :

  1. jdbc:mysql To express an agreement , adopt jdbc Mode of connection mysql;
  2. localhost host , It can also be ip Address ;
  3. 3306 Express mysql Listening port ;
  4. mysqlforjdbctest Connect to mysql Which database .

See code Notes for the rest :

package com.hxh.jdbc;

import com.mysql.jdbc.Driver;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/** * @author  Xiaohuang Xiaohuang is no longer confused  * @version 1.0 */
public class JDBC01 {
    
    public static void main(String[] args) throws SQLException {
    
        // 1.  Registration drive 
        Driver driver = new Driver();  //  establish driver object 

        // 2.  Get connected 
        // jdbc:mysql  To express an agreement , adopt jdbc Mode of connection mysql
        // localhost  host , It can also be ip Address 
        // 3306  Express  mysql  Listening port 
        // mysqlforjdbctest  Connect to  mysql  Which database 
        String url = "jdbc:mysql://localhost:3306/mysqlforjdbctest";
        //  take   Put the user name and password in  Properties  In the object 
        Properties properties = new Properties();
        properties.setProperty("user", "root");  //  user 
        properties.setProperty("password", "111");  //  password ( Fill in the password corresponding to your user name )
        //  According to the given  url  Connect to database 
        Connection connect = driver.connect(url, properties);

        // 3.  perform  sql
        String sql = "INSERT INTO student VALUES(null, ' Your beans ', ' Woman ', '2005-05-17', '13521987643')";
        // statement  For execution static SQL Statement and returns the resulting object 
        Statement statement = connect.createStatement();
        int rows = statement.executeUpdate(sql);  //  If it is  DML  sentence , The number of affected rows is returned 
        System.out.println(rows > 0 ? " Successful operation !" : " operation failed !");

        // 4.  Close the connection 
        statement.close();
        connect.close();
    }
}

Operation results and table changes :
 Insert picture description here
 Insert picture description here

2.3 Get the database connection 5 Ways of planting

The way 1️⃣ obtain Driver Implementation class object

Driver driver = new com.mysql.jdbc.Driver();
String url = "jdbc:mysql://localhost:3306/mysqlforjdbctest";
Properties properties = new Properties();
properties.setProperty("user", "root");  //  user 
properties.setProperty("password", "111");  //  password 
Connection connection = driver.connect(url, properties);

  The code uses com.mysql.jdbc.Driver(), It belongs to static loading , Poor flexibility , Strong dependence , Therefore, mode 2 is introduced .

The way 2️⃣ Use the reflection mechanism to get

Class clazz = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver)clazz.newInstance(); 
String url = "jdbc:mysql://localhost:3306/mysqlforjdbctest";
Properties properties = new Properties();
properties.setProperty("user", "root");  //  user 
properties.setProperty("password", "111");  //  password 
Connection connection = driver.connect(url, properties);

The way 3️⃣ Use DriverManager Replace Driver Unified management , relatively speaking , More scalable

Class clazz = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver)clazz.newInstance();
String url = "jdbc:mysql://localhost:3306/mysqlforjdbctest";
String user = "root";
String password = "111";
DriverManager.registerDriver(driver);  //  register Driver drive 
Connection connection = DriverManager.getConnection(url, user, password);

The way 4️⃣ Use Class.forName Automatically complete the registration drive , The code is more concise

Class clazz = Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mysqlforjdbctest";
String user = "root";
String password = "111";
Connection connection = DriverManager.getConnection(url, user, password);

  The following figure for Driver Class source code , It can be seen that , Exception handling in static code block , When the class is loaded, it will execute . And in the DriverManager.register(new Driver()) In fact, you are registering the driver , Because of the simplicity of the code , Mode 4 is also the most used mode in actual development .
 Insert picture description here

The way 5️⃣ Use profile , In fact, it is the optimization of mode 4 , Make connecting to the database more flexible ~

  1. First , stay src New file in directory mysql.properties;

  2. mysql.properties Save the user name in the configuration file 、 password 、url And driver Information , And save . Here's the picture :
     Insert picture description here

  3. In the corresponding class , Write the corresponding code

//  adopt  Properties  Object to get the information of the 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 url = properties.getProperty("url");
String driver = properties.getProperty("driver");
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, user, password);

3 ResultSet Result set

3.1 ResultSet Result set description

brief introduction :

  • Express Data table of database result set , Typically generated by executing statements that query the database ;
  • ResultSet object Keep 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 of ResultSet In the object Returns... When there are no more rows false, combination while A loop can traverse the result set .

3.2 ResultSet Result set cases

First , First execute the following code , by student Table add data , To facilitate the test .

INSERT INTO student VALUES (NULL, ' Monkey D Luffy ', ' male ', '2001-06-18', '13624567845');
INSERT INTO student VALUES (NULL, ' Joba ', ' male ', '2006-05-21', '13824063845');

The sample code is as follows :
In the code ,statement Methods executeQuery(sql) Returns a single ResultSet The object of . See the code Notes for details :

package com.hxh.jdbc;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Date;
import java.util.Properties;

/** * @author  Xiaohuang Xiaohuang is no longer confused  * @version 1.0 */
public class ResultSetTest {
    
    public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
    
        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 url = properties.getProperty("url");
        String driver = properties.getProperty("driver");

        // 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
        String sql = "SELECT id, name, sex, birthday FROM student";
        //  Perform a given SQL sentence , This statement returns a single  ResultSet  object 
        ResultSet resultSet = statement.executeQuery(sql);

        // 5.  Use while Take out the data 
        while (resultSet.next()){
      //  Move the cursor back , If there is no more line , Then exit the loop 
            int id = resultSet.getInt(1);  //  Get the first column of the row 
            String name = resultSet.getString(2);  //  Get the second column of the row 
            String sex = resultSet.getString(3);  //  Get the third column of the row 
            Date date = resultSet.getDate(4);  //  Gets the fourth column of the row 
            System.out.println(id + "\t" + name + "\t" + sex + "\t" + date);
        }

        // 6.  Close the connection 
        resultSet.close();
        statement.close();
        connection.close();
    }
}

Achieve results :
 Insert picture description here


4 Statement

4.1 Statement Description and SQL Inject

brief introduction :

  • Statement Object is used to perform static SQL Statement and returns the resulting object ;
  • After the connection is established , Need to access the database . Whether it's executing orders or SQL sentence , Both can pass Statement( There is sql Inject )、PreparedStatement( Preprocessing )、CallableStatement( stored procedure ) To carry out ;
  • adopt Statement Object to perform SQL sentence , There is SQL Injection risk ! Guard against SQL Inject , By using Statement Extended from PreparedStatement replace Statement that will do .

What is the SQL Inject ?
answer :SQL Injection is the use of some systems that do not adequately check the data entered by the user , And injecting illegal SQL Statement segment or command , Malicious attack database !
 Insert picture description here

4.2 Use Statement Simulated Login , demonstration SQL Injection risk

First , Through the following sentence , Create a new table in the database ,admin, Store user name and password :

CREATE TABLE admin
(                                             --  Administrator table 
    name     VARCHAR(20) NOT NULL DEFAULT '', --  user name 
    pwd      VARCHAR(20) NOT NULL DEFAULT ''  --  password 
);

INSERT INTO admin VALUES ('nezuko', '123456');
INSERT INTO admin VALUES ('lingling', '111111');

 Insert picture description here

The sample code is as follows :

package com.hxh.jdbc;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Date;
import java.util.Properties;
import java.util.Scanner;

/** * @author  Xiaohuang Xiaohuang is no longer confused  * @version 1.0 */
public class LoginTest {
    
    public static void main(String[] args) throws IOException, SQLException, ClassNotFoundException {
    
        Scanner scanner = new Scanner(System.in);

        //  The user enters the user name and password 
        System.out.print(" user name :");
        String admin_name = scanner.nextLine();
        System.out.print(" password :");
        String admin_pwd = scanner.nextLine();

        //  adopt Properties Object to get configuration file information 
        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 url = properties.getProperty("url");
        String driver = properties.getProperty("driver");

        // 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
        String sql = "SELECT name, pwd FROM admin WHERE name ='"
                + admin_name + "' AND pwd = '" + admin_pwd + "'";
        //  Perform a given SQL sentence , This statement returns a single  ResultSet  object 
        ResultSet resultSet = statement.executeQuery(sql);
        if(resultSet.next()){
    //  If you find a record , It means that the user exists 
            System.out.println(" Login successful !");
        }else {
    
            System.out.println(" Login failed !");
        }

        // 5.  Close the connection 
        resultSet.close();
        statement.close();
        connection.close();
    }
}

Demo session :

  1. Try Enter the correct user name and password
     Insert picture description here
  2. Try Enter wrong user name and password
     Insert picture description here
  3. User malicious SQL Inject :
     Insert picture description here

because Statement There is no preprocessing of user input , The logic to determine whether to log in happens to be the splicing of the user name and password entered by the user , This leads to the malicious injection of universal user name and password , Pass the inspection ~~


4.3 PreparedStatement Preprocessing queries

brief introduction :

  • PreparedStatement Class diagram :
     Insert picture description here
  • PreparedStatement Executive SQL The parameters in the statement are expressed in (?) To express , call PreparedStatement Object's setXxx() Method setting parameters . The first parameter is to be set SQL Parameter index in statement ( from 1 Start ), The second one is set up SQL The value of the parameter in the statement ;
  • executeQuery(), return ResultSet Result set object ;
  • executeUpdate(), Perform the update , For example, add, delete, and change operations .

PreparedStatement Benefits :

  1. No need to use + To splice sql sentence , It can reduce grammar errors to some extent ;
  2. Effectively solved sql Injection problem ;
  3. Greatly reduce the number of compilations , More efficient .

4.4 Use pretreatment to solve SQL Inject

Or the previous login example , It just USES PreparedStatement, The specific code is as follows , Step visible notes :

package com.hxh.jdbc;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Date;
import java.util.Properties;
import java.util.Scanner;

/** * @author  Xiaohuang Xiaohuang is no longer confused  * @version 1.0 */
public class LoginTest {
    
    public static void main(String[] args) throws IOException, SQLException, ClassNotFoundException {
    
        Scanner scanner = new Scanner(System.in);

        //  The user enters the user name and password 
        System.out.print(" user name :");
        String admin_name = scanner.nextLine();
        System.out.print(" password :");
        String admin_pwd = scanner.nextLine();

        //  adopt Properties Object to get configuration file information 
        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 url = properties.getProperty("url");
        String driver = properties.getProperty("driver");

        // 1.  Registration drive 
        Class.forName(driver);

        // 2.  Get connected 
        Connection connection = DriverManager.getConnection(url, user, password);

        // 3.  obtain  PreparedStatement
        // 3.1  organization Sql, ?  Equivalent to placeholder 
        String sql = "SELECT name, pwd FROM admin WHERE name = ? AND pwd = ?";
        // 3.2 preparedStatement  Object implementation  PreparedStatement Interface 
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        // 3.3  to  ?  assignment 
        preparedStatement.setString(1, admin_name);
        preparedStatement.setString(2, admin_pwd);

        // 4.  perform  select  Use  executeQuery,  If the execution is  dml sentence ,  Then use  executeUpdate
        ResultSet resultSet = preparedStatement.executeQuery();
        if(resultSet.next()){
    //  If you find a record , It means that the user exists 
            System.out.println(" Login successful !");
        }else {
    
            System.out.println(" Login failed !");
        }

        // 5.  Close the connection 
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }
}

Achieve results :
 Insert picture description here
It's solved sql Injection problem !


At the end

The above is the whole content of this article , The follow-up will continue Free update , If the article helps you , Please use your hands Point a praise + Focus on , Thank you very much ️ ️ ️ !
If there are questions , Welcome to the private letter or comment area !
 Insert picture description here

Mutual encouragement :“ You make intermittent efforts and muddle through , It's all about clearing the previous efforts .”
 Insert picture description here

原网站

版权声明
本文为[Xiaohuang Xiaohuang is no longer confused]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206210615019705.html