当前位置:网站首页>MySQL learning record 11jdbcstatement object, SQL injection problem and Preparedstatement object
MySQL learning record 11jdbcstatement object, SQL injection problem and Preparedstatement object
2022-07-06 08:26:00 【Jatine】
List of articles
MySQL Learning record 11JDBCstatement object 、SQL Injection problems and PreparedStatement object
11.1statement object
Jdbc Medium statement Object to send... To the database SQL sentence , Want to complete the addition, deletion, modification and query of the database , You only need to send the add, delete, change and query statement to the database through this object .
Statement Object's executeUpdate Method , Used to send add... To the database 、 Delete 、 Changed sql sentence ,executeUpdate After the execution , Will return an integer ( That is, the number of rows affected ).
Statement.executeQuery Method is used to send query statements to the database ,executeQuery Method to return ResultSet object .
CRUD operation -create
Use executeUpdate(String sql) Method to complete the data adding operation , Example operation :
Statement statement = connection.createStatement();
String sql = "insert into user(... ) values(... . ) ";
int num = statement.executeUpdate(sql);
if (num > 0) {
System.out.println(" Insert the success !!! ");
}
CRUD operation -delete
Use executeUpdate(String sql) Method to delete data , Example operation :
Statement statement = connection.createStatement();
String sql = "delete from user where id = 1";
int num = statement.executeUpdate(sql);
if (num > 0) {
System.out.println(" Delete successful !!! ");
}
CRUD operation -update
Use executeUpdate(String sql) Method to complete the data modification operation , Example operation :
Statement statement = connection.createStatement();
String sql = "update user set name = '' where name = '' ";
int num = statement.executeUpdate(sql);
if (num > 0) {
System.out.println(" Modification successful !!! ");
}
CRUD operation -read
Use executeUpdate(String sql) Method to complete data query operation , Example operation :
Statement statement = connection.createStatement();
String sql = "select * from user where id = 1";
ResultSet resultSet = statement.executeUpdate(sql);
where(resultSet .next()){
// Depending on the data type of the acquired column , Respectively called resultSet The corresponding method of mapping to java In the object
}
11.1.1 Code implementation ( Additions and deletions )
First write the database configuration file :
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false
username=root
password=123456
Secondly, it is compiled jdbc Tool class :
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JdbcUtils {
private static String driver = null;
private static String url = null;
private static String username = null;
private static String password = null;
static {
try {
InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(in);
// from db.properties Read these four information in
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
//1. The driver only loads once
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
// Get the connection
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
// Release the connection
public static void release(Connection conn, Statement st, ResultSet rs) throws SQLException {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (conn != null) {
conn.close();
}
}
}
Insert the test :
import com.jatine.lesson02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestInsert {
public static void main(String[] args) throws SQLException {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection(); // Get database connection , So it's connected , Don't write those configurations anymore
st = conn.createStatement(); // get SQL Execution object of
String sql = "INSERT INTO users(id,`NAME`,`PASSWORD`,`email`,`birthday`)" +
"VALUES(4,'zhaoliu','123456','[email protected]','2020-01-01')";
int i = st.executeUpdate(sql); // hold sql Statement is thrown in and executed ,i Is the number of rows affected
if (i > 0) {
System.out.println(" Insert the success !");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.release(conn, st, rs);
}
}
}

View the results in the database table :
Insert the success !
Now that the inserted code is successful , Then delete :
import com.jatine.lesson02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestDelete {
public static void main(String[] args) throws SQLException {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection(); // Get database connection , So it's connected , Don't write those configurations anymore
st = conn.createStatement(); // get SQL Execution object of
String sql = "DELETE FROM users WHERE id = 4";
int i = st.executeUpdate(sql); // hold sql Statement is thrown in and executed ,i Is the number of rows affected
if (i > 0) {
System.out.println(" Delete successful !");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.release(conn, st, rs);
}
}
}
Can be observed , The only difference from inserting test code is sql sentence , At most, the prompt of successful modification operation , Nothing else needs to be changed .
Run code :
View database table data :
Delete successful !
Another update :
import com.jatine.lesson02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestUpdate {
public static void main(String[] args) throws SQLException {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection(); // Get database connection , So it's connected , Don't write those configurations anymore
st = conn.createStatement(); // get SQL Execution object of
String sql = "UPDATE users SET `NAME`='madongmei',`email`='[email protected]' WHERE id = 1;";
int i = st.executeUpdate(sql); // hold sql Statement is thrown in and executed ,i Is the number of rows affected
if (i > 0) {
System.out.println(" The update is successful !");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.release(conn, st, rs);
}
}
}


The update is successful !
Inquire about :
import com.jatine.lesson02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestSelect {
public static void main(String[] args) throws SQLException {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection(); // Get database connection , So it's connected , Don't write those configurations anymore
st = conn.createStatement(); // get SQL Execution object of
String sql = "select * from users where id = 1";
rs = st.executeQuery(sql); // After the query, a result set will be returned
while (rs.next()) {
System.out.println(rs.getString("NAME"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.release(conn, st, rs);
}
}
}

11.1.2SQL Injection problem
SQL Injection means web The application does not judge or filter the validity of the user's input data , Attackers can web Add extra... At the end of a predefined query statement in the application SQL sentence , Implement illegal operation without the administrator's knowledge , In this way, the database server is cheated to execute any unauthorized query , So we can get the corresponding data information .
SQL Injection is one of the most common network attacks , It's not using the operating system BUG To achieve an attack , It's about the negligence of programmers , adopt SQL sentence , Login without account , Even tampering with the database .
11.1.2.1SQL The general idea of injection attack
- Look for SQL Injection location
- Judge the server type and background database type
- For different server and database characteristics SQL Injection attack
Case study :
import com.jatine.lesson02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SqlInjection {
public static void main(String[] args) {
login("madongei", "123456");
}
public static void login(String username, String password) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection(); // Get database connection , So it's connected , Don't write those configurations anymore
st = conn.createStatement(); // get SQL Execution object of
String sql = "select * from users where `NAME`='" + username + "' AND `PASSWORD` = '" + password + "'";
rs = st.executeQuery(sql); // After the query, a result set will be returned
while (rs.next()) {
System.out.println(rs.getString("NAME"));
System.out.println(rs.getString("PASSWORD"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
JdbcUtils.release(conn, st, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
If you can log in normally , Then the user name should be output 、 Result of password
but :
If you add the above code login("madongei", "123456"); Change it to login("'or '1=1","123456");
All user names and passwords have been stolen .
11.2PreparedStatement object
prevent sql Injection and higher efficiency
1、 newly added
import com.jatine.lesson02.utils.JdbcUtils;
import java.sql.*;
import java.util.Date;
public class TestInsert {
public static void main(String[] args) throws SQLException {
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection(); // Get database connection , So it's connected , Don't write those configurations anymore
// difference Use ? Instead of parameters
String sql = "INSERT INTO users(id,`NAME`,`PASSWORD`,`email`,`birthday`)" + "VALUES(?,?,?,?,?)";
st = conn.prepareStatement(sql);// precompile sql, First write sql, Don't execute
// Assign parameters manually
st.setInt(1, 4);
st.setString(2, "haha");
st.setString(3, "123456");
st.setString(4, "[email protected]");
// Be careful sql.Date
// util.Date
st.setDate(5, new java.sql.Date(new Date().getTime()));
// perform
int i = st.executeUpdate(); // hold sql Statement is thrown in and executed ,i Is the number of rows affected
if (i > 0) {
System.out.println(" Insert the success !");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.release(conn, st, rs);
}
}
}


2、 Delete
import com.jatine.lesson02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
public class TestDelete {
public static void main(String[] args) throws SQLException {
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection(); // Get database connection , So it's connected , Don't write those configurations anymore
// difference Use ? Instead of parameters
String sql = "delete from users where id = ?";
st = conn.prepareStatement(sql);// precompile sql, First write sql, Don't execute
// Assign parameters manually
st.setInt(1,4);
// perform
int i = st.executeUpdate(); // hold sql Statement is thrown in and executed ,i Is the number of rows affected
if (i > 0) {
System.out.println(" Delete successful !");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.release(conn, st, rs);
}
}
}


3、 to update
import com.jatine.lesson02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TestUpdate {
public static void main(String[] args) throws SQLException {
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection(); // Get database connection , So it's connected , Don't write those configurations anymore
// difference Use ? Instead of parameters
String sql = "update users set `NAME` = ? where id = ?;";
st = conn.prepareStatement(sql);// precompile sql, First write sql, Don't execute
// Assign parameters manually
st.setString(1, "xialuo");
st.setInt(2, 1);
// perform
int i = st.executeUpdate(); // hold sql Statement is thrown in and executed ,i Is the number of rows affected
if (i > 0) {
System.out.println(" The update is successful !");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.release(conn, st, rs);
}
}
}


4、 Inquire about
import com.jatine.lesson02.utils.JdbcUtils;
import java.sql.*;
public class TestSelect {
public static void main(String[] args) throws SQLException {
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection(); // Get database connection , So it's connected , Don't write those configurations anymore
// difference Use ? Instead of parameters
String sql = "select * from users where id = ?";
st = conn.prepareStatement(sql);// precompile sql, First write sql, Don't execute
// Assign parameters manually
st.setInt(1, 1);
// perform
rs = st.executeQuery(); // hold sql Statement is thrown in and executed ,i Is the number of rows affected
if (rs.next()) {
System.out.println(rs.getString("NAME"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.release(conn, st, rs);
}
}
}

5、 prevent sql Inject
Normal business :
import com.jatine.lesson02.utils.JdbcUtils;
import java.sql.*;
public class SqlInjection {
public static void main(String[] args) {
login("xialuo", "123456");
//login("'or '1=1","123456");
}
public static void login(String username, String password) {
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection(); // Get database connection , So it's connected , Don't write those configurations anymore
String sql = "select * from users where `NAME`=? AND `PASSWORD`=?";
st = conn.prepareStatement(sql); // precompile sql
st.setString(1,username);
st.setString(2,password);
rs = st.executeQuery(); // After the query, a result set will be returned
while (rs.next()) {
System.out.println(rs.getString("NAME"));
System.out.println(rs.getString("PASSWORD"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
JdbcUtils.release(conn, st, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

Splicing sql:
import com.jatine.lesson02.utils.JdbcUtils;
import java.sql.*;
public class SqlInjection {
public static void main(String[] args) {
//login("xialuo", "123456");
login("''or 1=1","123456");
}
public static void login(String username, String password) {
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection(); // Get database connection , So it's connected , Don't write those configurations anymore
String sql = "select * from users where `NAME`=? AND `PASSWORD`=?";
st = conn.prepareStatement(sql); // precompile sql
st.setString(1,username);
st.setString(2,password);
rs = st.executeQuery(); // After the query, a result set will be returned
while (rs.next()) {
System.out.println(rs.getString("NAME"));
System.out.println(rs.getString("PASSWORD"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
JdbcUtils.release(conn, st, rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

No results , There was no error
边栏推荐
- C语言 - 位段
- Artcube information of "designer universe": Guangzhou implements the community designer system to achieve "great improvement" of urban quality | national economic and Information Center
- Modify the video name from the name mapping relationship in the table
- Summary of phased use of sonic one-stop open source distributed cluster cloud real machine test platform
- 你想知道的ArrayList知识都在这
- Use br to back up tidb cluster data to S3 compatible storage
- [brush questions] top101 must be brushed in the interview of niuke.com
- 2022.02.13 - NC002. sort
- Day29-t77 & t1726-2022-02-13-don't answer by yourself
- Summary of MySQL index failure scenarios
猜你喜欢

All the ArrayList knowledge you want to know is here

Convolution, pooling, activation function, initialization, normalization, regularization, learning rate - Summary of deep learning foundation

让学指针变得更简单(三)

【MySQL】数据库的存储过程与存储函数通关教程(完整版)

Make learning pointer easier (3)

Leetcode question brushing (5.28) hash table
![[research materials] 2021 China online high growth white paper - Download attached](/img/51/bea6179e4fac88f8b550b4213a2bca.jpg)
[research materials] 2021 China online high growth white paper - Download attached

【MySQL】日志

hcip--mpls

The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
随机推荐
LDAP應用篇(4)Jenkins接入
Golang DNS write casually
vulnhub hackme: 1
从 TiDB 集群迁移数据至另一 TiDB 集群
Migrate data from a tidb cluster to another tidb cluster
指针进阶---指针数组,数组指针
1. Color inversion, logarithmic transformation, gamma transformation source code - miniopencv from zero
Asia Pacific Financial Media | designer universe | Guangdong responds to the opinions of the national development and Reform Commission. Primary school students incarnate as small community designers
华为云OBS文件上传下载工具类
Nacos Development Manual
使用 TiUP 升级 TiDB
使用 TiDB Lightning 恢复 S3 兼容存储上的备份数据
hcip--mpls
VMware 虚拟化集群
[brush questions] top101 must be brushed in the interview of niuke.com
Use dumping to back up tidb cluster data to S3 compatible storage
Tidb backup and recovery introduction
Hcip day 16
Beijing invitation media
leetcode刷题 (5.29) 哈希表