当前位置:网站首页>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
边栏推荐
- Is it safe to open an account in Zheshang futures?
- 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
- 2022 Inner Mongolia latest construction tower crane (construction special operation) simulation examination question bank and answers
- TiDB备份与恢复简介
- 升级 TiDB Operator
- vulnhub hackme: 1
- 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
- On the day of resignation, jd.com deleted the database and ran away, and the programmer was sentenced
- Cisp-pte practice explanation
- Nacos Development Manual
猜你喜欢

Asia Pacific Financial Media | "APEC industry +" Western Silicon Valley invests 2trillion yuan in Chengdu Chongqing economic circle to catch up with Shanghai | stable strategy industry fund observatio

Easy to use tcp-udp_ Debug tool download and use

Nacos Development Manual

NFT smart contract release, blind box, public offering technology practice -- contract

Golang DNS write casually

Ruffian Heng embedded bimonthly, issue 49
![[brush questions] top101 must be brushed in the interview of niuke.com](/img/55/5ca957e65d48e19dbac8043e89e7d9.png)
[brush questions] top101 must be brushed in the interview of niuke.com

CISP-PTE实操练习讲解

Hungry for 4 years + Ali for 2 years: some conclusions and Thoughts on the road of research and development

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
随机推荐
2022.02.13 - NC001. Reverse linked list
Chinese Remainder Theorem (Sun Tzu theorem) principle and template code
Summary of phased use of sonic one-stop open source distributed cluster cloud real machine test platform
使用 BR 备份 TiDB 集群数据到兼容 S3 的存储
logback1.3. X configuration details and Practice
Make learning pointer easier (3)
在 uniapp 中使用阿里图标
LDAP Application Section (4) Jenkins Access
From monomer structure to microservice architecture, introduction to microservices
Restore backup data on S3 compatible storage with tidb lightning
Pointer advanced --- pointer array, array pointer
Personalized online cloud database hybrid optimization system | SIGMOD 2022 selected papers interpretation
让学指针变得更简单(三)
The resources of underground pipe holes are tight, and the air blowing micro cable is not fragrant?
你想知道的ArrayList知识都在这
Is it safe to open an account in Zheshang futures?
从表中名称映射关系修改视频名称
sys. argv
Golang DNS 随便写写
Vocabulary notes for postgraduate entrance examination (3)