当前位置:网站首页>[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 luckThis article is from the column :JDBC From introduction to practice
Welcome to the support subscription column ️
List of articles
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 :
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
- Registration drive - load Driver class ;
- Get the connection - obtain Connection;
- Perform the operations of adding, deleting, modifying and querying - send out SQL to mysql perform ;
- 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 :
- 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 .
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 :

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 .
The way 5️⃣ Use profile , In fact, it is the optimization of mode 4 , Make connecting to the database more flexible ~
First , stay
srcNew file in directorymysql.properties;mysql.propertiesSave the user name in the configuration file 、 password 、url And driver Information , And save . Here's the picture :
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 ;
ResultSetobject Keep a cursor pointing to its current data row . first , The cursor is before the first line ;nextMethod 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 :
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 !
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');

️ 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 :
- Try Enter the correct user name and password :

- Try Enter wrong user name and password :

- User malicious SQL Inject :

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 :

PreparedStatementExecutive SQL The parameters in the statement are expressed in (?) To express , callPreparedStatementObject'ssetXxx()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(), returnResultSetResult set object ;executeUpdate(), Perform the update , For example, add, delete, and change operations .
PreparedStatement Benefits :
- No need to use + To splice sql sentence , It can reduce grammar errors to some extent ;
- Effectively solved sql Injection problem ;
- 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 :
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 !
Mutual encouragement :“ You make intermittent efforts and muddle through , It's all about clearing the previous efforts .”
边栏推荐
- nametuple的源码为什么要使用.replace(‘,‘, ‘ ‘).split()而不是.split(‘,‘)
- 当今的数学是否过于繁琐?
- leetcode 675. Cutting down trees for golf competitions - (day29)
- [data mining] final review Chapter 1
- 如何通过JDBC访问MySQL数据库?手把手实现登录界面(图解+完整代码)
- Chapter 2: Data Model (final review of database)
- [data mining] final review Chapter 5
- 记录 Navicat 连接 PostgreSQL 无法显示对应表的问题
- Several optimization methods of deep learning
- How to limit intranet speed
猜你喜欢

Aurora 8b10b IP use - 02 - IP function design skills

Aurora8b10b IP usage-02-ip function design skills

5254. dynamic planning of selling wood blocks

Pyshark tutorial

Aurora8b10b IP use-04-ip routine application example
![[is the network you are familiar with really safe?] Wanziwen](/img/b4/6092ab3fd728e5d453ec38b089d027.png)
[is the network you are familiar with really safe?] Wanziwen

Aurora8b10b IP usage-03-ip configuration application guide

Broadcast mechanism of numpy

Record the problem that Navicat connection PostgreSQL cannot display the corresponding table

创新项目实训:数据分析与可视化
随机推荐
Answer the question: what do you think AgI should adopt?
docker 安装mysql
C语言实现模拟银行存取款管理系统课程设计(纯C语言版)
【JDBC从入门到实战】JDBC基础通关教程(全面总结上篇)
leetcode 675. Cutting down trees for golf competitions - (day29)
笔记 How Powerful are Spectral Graph Neural Networks
[data mining] final review Chapter 3
Idea usage record
FPGA - 7系列 FPGA SelectIO -02- 源语简介
nametuple的源码为什么要使用.replace(‘,‘, ‘ ‘).split()而不是.split(‘,‘)
Broadcast mechanism of numpy
Unity隐藏目录和隐藏文件
Leetcode 75 - three implementation methods of color classification [medium]
【利用MSF工具内网复现MS08-067】
Basic use of JPA
Pycharm的快捷键Button 4 Click是什么?
Port occupancy resolution
User defined thread pool
Recursively establish a chained binary tree, complete the traversal of the first, middle and last order and other functions (with source code)
tf. compat. v1.pad