当前位置:网站首页>[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
边栏推荐
- Explore Netease's large-scale automated testing solutions see here see here
- What is the difference between 14Cr1MoR container plate and 14Cr1MoR (H)? Chemical composition and performance analysis of 14Cr1MoR
- 13mnnimo5-4 German standard steel plate 13MnNiMo54 boiler steel 13MnNiMo54 chemical properties
- Top k questions of interview
- Alibaba P8 painstakingly sorted it out. Summary of APP UI automated testing ideas. Check it out
- Client does not support authentication protocol requested by server; consider upgrading MySQL client
- PHP CI (CodeIgniter) log level setting
- MySQL Basics
- Yu Wenwen, Hu Xia and other stars take you to play with the party. Pipi app ignites your summer
- Golang decorator mode and its use in NSQ
猜你喜欢
斑马识别成狗,AI犯错的原因被斯坦福找到了
Recommendation of good books on learning QT programming
Threejs Part 2: vertex concept, geometry structure
What material is sa537cl1? Sa537cl1 corresponds to the national standard material
Shentong express expects an annual loss of nearly 1billion
What material is 13crmo4-5 equivalent to in China? 13crmo4-5 chemical composition 13crmo4-5 mechanical properties
2022.02.14_ Daily question leetcode five hundred and forty
NSQ source code installation and operation process
智慧之道(知行合一)
Add color to the interface automation test framework and realize the enterprise wechat test report
随机推荐
关于学习Qt编程的好书精品推荐
远程办公之如何推进跨部门项目协作 | 社区征文
How to promote cross department project collaboration | community essay solicitation
Shentong express expects an annual loss of nearly 1billion
function overloading
What is the difference between 14Cr1MoR container plate and 14Cr1MoR (H)? Chemical composition and performance analysis of 14Cr1MoR
Cocos Creator 2. X automatic packaging (build + compile)
JSON 与 BSON 区别
Client does not support authentication protocol requested by server; consider upgrading MySQL client
2022 love analysis · panoramic report of digital manufacturers of state-owned enterprises
LeetCode 1657. Determine whether the two strings are close
Le zèbre a été identifié comme un chien, et la cause de l'erreur d'AI a été trouvée par Stanford
PHP converts a one-dimensional array into a two-dimensional array
Recommendation of good books on learning QT programming
香港理工大学|数据高效的强化学习和网络流量动态的自适应最优周界控制
MySQL converts comma separated attribute field data from column to row
手机注册股票开户安全吗 开户需要钱吗
mysql用户管理
NSQ source code installation and operation process
[sword finger offer] 58 - I. flip the word order