当前位置:网站首页>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
边栏推荐
- MFC sends left click, double click, and right click messages to list controls
- Sort according to a number in a string in a column of CSV file
- On the day of resignation, jd.com deleted the database and ran away, and the programmer was sentenced
- MySQL learning record 10getting started with JDBC
- Leetcode question brushing record | 203_ Remove linked list elements
- "Designer universe" APEC design +: the list of winners of the Paris Design Award in France was recently announced. The winners of "Changsha world center Damei mansion" were awarded by the national eco
- Pyqt5 development tips - obtain Manhattan distance between coordinates
- String to leading 0
- 你想知道的ArrayList知识都在这
- 图像融合--挑战、机遇与对策
猜你喜欢
Summary of phased use of sonic one-stop open source distributed cluster cloud real machine test platform
化不掉的钟薛高,逃不出网红产品的生命周期
2022.02.13 - NC002. sort
Asia Pacific Financial Media | art cube of "designer universe": Guangzhou community designers achieve "great improvement" in urban quality | observation of stable strategy industry fund
Golang DNS 随便写写
指针进阶---指针数组,数组指针
【刷题】牛客网面试必刷TOP101
Zhong Xuegao, who cannot be melted, cannot escape the life cycle of online celebrity products
根据csv文件某一列字符串中某个数字排序
NFT smart contract release, blind box, public offering technology practice -- jigsaw puzzle
随机推荐
Migrate data from SQL files to tidb
使用 BR 备份 TiDB 集群数据到兼容 S3 的存储
Image fusion -- challenges, opportunities and Countermeasures
[MySQL] database stored procedure and storage function clearance tutorial (full version)
化不掉的钟薛高,逃不出网红产品的生命周期
【MySQL】数据库的存储过程与存储函数通关教程(完整版)
[research materials] 2022 China yuancosmos white paper - Download attached
指针和数组笔试题解析
Verrouillage [MySQL]
JVM performance tuning and practical basic theory - Part 1
使用 BR 恢复 S3 兼容存储上的备份数据
Huawei cloud OBS file upload and download tool class
leetcode刷题 (5.31) 字符串
升级 TiDB Operator
C language - bit segment
面向个性化需求的在线云数据库混合调优系统 | SIGMOD 2022入选论文解读
Leetcode question brushing record | 203_ Remove linked list elements
VMware 虚拟化集群
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
Pointer advanced --- pointer array, array pointer