当前位置:网站首页>[JDBC] API parsing
[JDBC] API parsing
2022-07-03 16:48:00 【Hold on for a long time】
Catalog
demonstration jdbc The business of
PreparedStatement solve SQL Inject
One 、DriverManager
DriverManager( Driver management ) effect :
1、 Registration drive
2、 Get database connection
1、 Registration drive :
Class.forName("com.mysql.jdbc.Driver");
Registration driven writing method , Not used on the surface DriverManager class , Choose Driver,ctrl+b Look at the source
package com.mysql.jdbc;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Driver extends NonRegisteringDriver implements java.sql.Driver {
public Driver() throws SQLException {
}
static {
try {
DriverManager.registerDriver(new Driver());
} catch (SQLException var1) {
throw new RuntimeException("Can't register driver!");
}
}
}
It has been used. DriverManager.registerDriver() Methods
stay MySQL5 Later driver package , You can omit the steps of registering the driver
Automatic loading jar In bag META-INF/services/java.sql.Driver File driver class
2、 Get the connection
static Connection getConnection(String url,String user,String password)
Parameters
1、url: Connection path
grammar :jdbc:mysql://ip Address ( domain name ): Port number / Database name ? Parameter key value pair 1& Parameter key value pair 2....
give an example :jdbc:mysql://127.0.0.1:3306/db1( This machine 127.0.0.1, Local domain name :localhost)
details : If the connection is local mysql The server , also mysql The default port number is 3306 , be url I could just write it as :jdbc:mysql:// Database name ? Parameter key value pairs, such as :jdbc:mysql:///db1
To configure userSSL=false Parameters , Disable secure connection mode , Resolve warning tips
2、user: user name
3、password: password
Resolve warning tips :
?userSSL=false
String url="jdbc:mysql://127.0.0.1:3306/db1?useSSL=false";
Two 、Connection
Connection( Database connection object ) effect :
1、 Access to perform SQL The object of
2、 Manage affairs
1、 Get hold sql object
- Common execution SQL object
Statement createStatement()
- precompile SQL Implementation SQL object : prevent SQL Inject
PrepareStatement prepareStatement(sql)
- Objects execute stored procedures
CallableStatement prepareCall(sql)
2、 Business management
mysql Business management
Open transaction :BEGIN;/START TRANSACTION(start transaction)
Commit transaction :COMMIT;
Roll back the transaction :ROLLBACK;
(MySQL Automatically commit transactions by default )
JDBC Business management :
Connection Interface defined 3 Corresponding methods
Open transaction :setAutoCommit(boolean autoCommit);true For auto commit transactions ,false For manual commit transactions ( Open transaction )
Commit transaction :commit()
Roll back the transaction :rollback()
demonstration jdbc The business of
Copy the previous classes to the package
package com.jdbc;
import com.mysql.jdbc.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCConnectionDemo {
public static void main(String[] args) throws Exception {
//1、 Registration drive
Class.forName("com.mysql.jdbc.Driver");
//2、 Get the connection
//url The format is :"jdbc:mysql://mysql Of ip: Port number / Operational database "
String url="jdbc:mysql://127.0.0.1:3306/kc_db01";
//username Is your mysql user name
String username="root";
//password Is your mysql password
String password="123456";
Connection conn= (Connection) DriverManager.getConnection(url, username, password);
//3、 Definition sql
String sql1="update emp set salary=6666 where ename='zhangsan'";
String sql2="update emp set salary=6666 where ename='lisi'";
//4、 Access to perform sql Of Statement object
Statement stat=conn.createStatement();
// Select the exception part to handle ,ctrl+alt+t Shortcut key generation
try {
// Open transaction
conn.setAutoCommit(false);
// perform sql
int count1=stat.executeUpdate(sql1);
// Processing results
System.out.println(" Number of rows affected :"+count1);
// Execution time sql
int count2=stat.executeUpdate(sql2);
// Processing results
System.out.println(" Number of rows affected :"+count2);
// Commit transaction
conn.commit();
} catch (Exception e) {
e.printStackTrace();
// Roll back the transaction ( Back before starting the transaction , That is, before dealing with anything )
conn.rollback();
}finally {
//7、 Release resources ( Open first and then release )
stat.close();
conn.close();
}
}
}
Before running the database emp surface :
Running results :
After running, the database emp surface :
try An exception occurred in , will By catch Capture , A rollback occurred , Rollback to before the transaction has been started , That is, before the data is modified , If it doesn't work , It may lead to one success and one failure , This is something we don't want to see . Transaction enabled , Rollback transaction is used , Multiple transactions can be guaranteed to succeed at the same time , Or fail at the same time .
3、 ... and 、Statement
Statemen effect :
1、 perform sql sentence
int executeUpdate(sql): perform DML( Addition, deletion and modification of data )、DDL( Addition, deletion and modification of tables and libraries ) sentence
Return value :(1)DML The number of lines affected by the statement (2)DDL After statement execution , Successful execution may also return 0
ResultSet executeQuery(sql): perform DQL( Query data ) sentence
Return value :ResultSet Result object
Four 、ResultSet
ResultSet( Result set object ) effect :
1. Encapsulates the DQL The result of the query statement
ResultSet stmt.executeQuery(sql): perform DQL sentence , return ResultSet object
Get query results
boolean next():(1) Move the cursor forward one line from the current position (2) Judge whether the current line is a valid line
Return value : The current row has data returned true, There is currently no data returned false.
xxx getXxx( Parameters ): get data
explain :xxx Represents the data type ; Such as int getInt( Parameters );String getString( Parameters );
Parameters : about int Is the number of the column , from 1 Start , about String Is the name of the column .
Use steps :
1、 Move the cursor down one line , And judge whether the line has data :next()
2、 get data :getXxx( Parameters )
Example :
while(rs.next()){
rs.getXxx( Parameters );
}
example :
package com.jdbc;
import com.mysql.jdbc.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JDBCDemo3_ResultSet {
public static void main(String[] args) throws Exception {
//1、 Registration drive
Class.forName("com.mysql.jdbc.Driver");
//2、 Get the connection
//url The format is :"jdbc:mysql://mysql Of ip: Port number / Operational database "
String url="jdbc:mysql://127.0.0.1:3306/kc_db01";
//username Is your mysql user name
String username="root";
//password Is your mysql password
String password="123456";
Connection conn= (Connection) DriverManager.getConnection(url, username, password);
//3、 Definition sql
String sql="select *from emp";
//4、 Access to perform sql Of Statement object
Statement stmt=conn.createStatement();
//5、 perform sql sentence
ResultSet rs=stmt.executeQuery(sql);
//6 Processing results
while(rs.next()){
// get data getXxx(); You can write the line in parentheses , You can also write column names
int id=rs.getInt(1);
String ename=rs.getString(2);
int salary=rs.getInt(3);
// Another way of writing : Write the name of the line
// int id=rs.getInt("id");
// String ename=rs.getString("ename");
// int salary=rs.getInt("salary");
System.out.println(id);
System.out.println(ename);
System.out.println(salary);
System.out.println("-----------");
}
//7、 Release resources ( Open first and then release )
rs.close();
stmt.close();
conn.close();
}
}
In the database emp surface
After running :
ResultSet Case study
demand : Inquire about account Account data , Encapsulated in the Account In the object , And store it in ArrayList Collection
Create a pojo package , Used to store objects .
Created a class , Provide getSet Method
package com.pojo;
public class Account {
private int id;
private String ename;
private int salary;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
// In order to better show , rewrite toString() Method
@Override
public String toString() {
return "Account{" +
"id=" + id +
", ename='" + ename + '\'' +
", salary=" + salary +
'}'+"\n";
}
}
jdbc In the class created under the package
package com.jdbc;
import com.mysql.jdbc.Connection;
import com.pojo.Account;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class JDBCDemo4_ResultSet {
public static void main(String[] args) throws Exception {
//1、 Registration drive
Class.forName("com.mysql.jdbc.Driver");
//2、 Get the connection
//url The format is :"jdbc:mysql://mysql Of ip: Port number / Operational database "
String url="jdbc:mysql://127.0.0.1:3306/kc_db01";
//username Is your mysql user name
String username="root";
//password Is your mysql password
String password="123456";
Connection conn= (Connection) DriverManager.getConnection(url, username, password);
//3、 Definition sql
String sql="select *from emp";
//4、 Access to perform sql Of Statement object
Statement stmt=conn.createStatement();
//5、 perform sql sentence
ResultSet rs=stmt.executeQuery(sql);
//6 Processing results
// Create a collection object
List<Account> list=new ArrayList<>();
while(rs.next()){
// establish Account object
Account account=new Account();
// get data getXxx(); You can write the line in parentheses , You can also write column names
int id=rs.getInt(1);
String ename=rs.getString(2);
int salary=rs.getInt(3);
// Assignment data
account.setId(id);
account.setEname(ename);
account.setSalary(salary);
list.add(account);
}
System.out.println(list);
//7、 Release resources ( Open first and then release )
rs.close();
stmt.close();
conn.close();
}
}
Running results :
5、 ... and 、PreparedStatement
PreparedStatement effect :
1、 precompile SQL Statement and execute : The prevention of SQL Injection problem
SQL Inject
SQL Injection is to modify pre-defined by operating input SQL sentence , The method used to execute code to attack the server .
Demonstrate normal login :
First, data record kc_db1 Under the emp The table is :
package com.jdbc;
import com.mysql.jdbc.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JDBCDemo5_UserLogin {
public static void main(String[] args) throws Exception {
//2、 Get the connection
//url The format is :"jdbc:mysql://mysql Of ip: Port number / Operational database "
String url="jdbc:mysql://127.0.0.1:3306/kc_db01";
//username Is your mysql user name
String username="root";
//password Is your mysql password
String password="123456";
Connection conn= (Connection) DriverManager.getConnection(url, username, password);
String name="zhangsan";
String pwd="1233";
//3、 Definition sql
String sql="select *from emp where ename='"+name+"'and password='"+pwd+"'" ;
System.out.println(" This article SQL The sentence is :"+sql);
//4、 Access to perform sql Of Statement object
Statement stat=conn.createStatement();
//5、 perform sql sentence
ResultSet rs = stat.executeQuery(sql);
//6 Processing results ,rs A value indicates that the search is successful
if(rs.next()){
System.out.println(" Login successful ");
}else{
System.out.println(" Login failed ");
}
//7、 Release resources ( Open first and then release )
rs.close();
stat.close();
conn.close();
}
}
Running results :
Enter other ( The reason for the failure is that there is no account with this password in the database ):
sql Inject Demo :
For this article sql It's not about passwords , Any account number
String name=" A casual name ";
String pwd=" ' or '1'='1";
Running results :
This article SQL The sentence is :select *from emp where ename=' A casual name 'and password=' ' or '1'='1'
sql The essence of injection is to change the original SQL sentence , Join in or after 1=1 Always true , So this sentence is true
PreparedStatement solve SQL Inject
① obtain PreparedStatement object
//sql Parameters in statement , Use ? Instead of
String sql="select *from user where username=? and password=?";
// adopt Connection Object acquisition , And pass in the corresponding sql sentence
PreparedStatement pstmt=conn.prepareStatement(sql);
② Set parameters
PreparedStatement object :setXxx( Parameters 1, Parameters 2): Expressed as a parameter 1(? The location of ) Assign value to parameter 2
Xxx: data type ; arbitrarily setInt( Parameters 1, Parameters 2)
Parameters :
- Parameters 1: Express ? Location number of , from 1 Start
- Parameters 2: ? Value
③ perform sql
executeUpdate();/excuteQuery(); There is no need to pass... In parentheses sql.
Create a class :
package com.jdbc;
import com.mysql.jdbc.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
public class JDBCDemo5_UserLogin {
public static void main(String[] args) throws Exception {
//2、 Get the connection
//url The format is :"jdbc:mysql://mysql Of ip: Port number / Operational database "
String url="jdbc:mysql://127.0.0.1:3306/kc_db01";
//username Is your mysql user name
String username="root";
//password Is your mysql password
String password="123456";
Connection conn= (Connection) DriverManager.getConnection(url, username, password);
String name=" A casual name ";
String pwd=" ' or '1'='1";
//3、 Definition sql
String sql="select *from emp where ename=? and password=?" ;
//4、 Acquired PreparedStatement object
PreparedStatement pstmt = conn.prepareStatement(sql);
// Set parameters
pstmt.setString(1, name);
pstmt.setString(2, pwd);
//5、 perform sql sentence
ResultSet rs =pstmt.executeQuery();
System.out.println(" This article SQL The sentence is :"+sql);
//6 Processing results ,rs A value indicates that the search is successful
if(rs.next()){
System.out.println(" Login successful ");
}else{
System.out.println(" Login failed ");
}
//7、 Release resources ( Open first and then release )
rs.close();
pstmt.close();
conn.close();
}
}
Running results :
This prevents sql Inject ,setXxx The parameters passed in will be escaped , Not spliced into strings, but \' or\ ' 1\' = \' 1\'
Enter the correct :
PrepareStatement principle
PrepareStatement benefits :
1、 precompile SQL, Higher performance
2、 prevent sql Inject .
my.ini The configuration file can see the log
log-output=FILE
general-log=1
general_log_file="D:\mysql.log"
slow-query-log=1
slow_query_log_file="D:\mysql_slow.log"
long_query_time=2
The precompile function is off by default
①:PreparedStatement Precompile function Turn on :userServerPrepStmts=true
stay sql sentence ? Then write the parameters
String url="jdbc:mysql://127.0.0.1:3306/kc_db01"?userServerPrepStmts=true;
When you open it, you will prepare precompile :
After closing, there is no Prepare Stage
边栏推荐
- What material is sa537cl1? Sa537cl1 corresponds to the national standard material
- MySQL Basics
- MySQL converts comma separated attribute field data from column to row
- Mysql 将逗号隔开的属性字段数据由列转行
- Interviewer: how does the JVM allocate and recycle off heap memory
- 什么是质押池,如何进行质押呢?
- ucore概述
- RF Analyze Demo搭建 Step by Step
- 线程池执行定时任务
- PyTorch 1.12发布,正式支持苹果M1芯片GPU加速,修复众多Bug
猜你喜欢
QT串口ui设计和解决显示中文乱码
MySQL converts comma separated attribute field data from column to row
QT serial port UI design and solution to display Chinese garbled code
What kind of material is 14Cr1MoR? Analysis of chemical composition and mechanical properties of 14Cr1MoR
消息队列消息丢失和消息重复发送的处理策略
Le zèbre a été identifié comme un chien, et la cause de l'erreur d'AI a été trouvée par Stanford
Network security web penetration technology
Netease UI automation test exploration: airtest+poco
ThreeJS 第二篇:顶点概念、几何体结构
CC2530 common registers for watchdog
随机推荐
Difference between JSON and bson
Cocos Creator 2. X automatic packaging (build + compile)
Visual SLAM algorithms: a survey from 2010 to 2016
Svn usage specification
Overview of satellite navigation system
Extraction of the same pointcut
Hong Kong Polytechnic University | data efficient reinforcement learning and adaptive optimal perimeter control of network traffic dynamics
PHP secondary domain name session sharing scheme
8 cool visual charts to quickly write the visual analysis report that the boss likes to see
【剑指 Offer】58 - I. 翻转单词顺序
One article takes you to understand machine learning
Capacités nécessaires à l'analyse des données
Necessary ability of data analysis
Develop team OKR in the way of "crowdfunding"
LeetCode 1658. Minimum operand to reduce x to 0
Aike AI frontier promotion (7.3)
What is the maximum number of concurrent TCP connections for a server? 65535?
Client does not support authentication protocol requested by server; consider upgrading MySQL client
NFT new opportunity, multimedia NFT aggregation platform okaleido will be launched soon
Central South University | through exploration and understanding: find interpretable features with deep reinforcement learning