PrepareStatement: execute SQL object
1. SQL injection problem : when splicing SQL, some special SQL keywords are involved in the splicing of strings. Will cause safety issues
- Enter your username and password: a'or'a' ='a
- Solve the problem of SQL injection: use PreparedStatement object to solve
- Precompiled SQL: parameter usage? As a placeholder
2. Steps :
-
Import the driver jar package
-
Register driver
-
Get Connection
-
Define SQL
Note: SQL uses? As a placeholder. Such as:
String sql = "select * from user where username = ? and password = ?";
- Get the object that executes the SQL statement
PreparedStatement Connection.prepareStatement(String sql)
pstmt = conn.prepareStatement(sql);
- Assign to?:
Method: setXxx (parameter 1, parameter 2), such as:
pstmt.setString(1,username);
pstmt.setString(2,password);
Parameter 1: The position number of ?, starting from 1
Parameter 2: The value of?
- Execute SQL and accept the returned result without passing sql statement:
rs = pstmt.executeQuery();
-
process result
-
Release resources
Full version code:
import util.JDBCUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class JDBCsafe {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名:");
String username = sc.nextLine();
System.out.println("请输入密码:");
String password = sc.nextLine();
boolean logincheck = new JDBCsafe().login2(username, password);
if (logincheck)
System.out.println("登录成功");
else
System.out.println("登录失败");
}
public boolean login2(String username,String password){
Connection conn = null;
ResultSet rs = null;
PreparedStatement pstmt = null;
if (username == null || password == null){
return false;
}
try {
conn = JDBCUtils.getConnection();
// 定义SQL
String sql = "select * from user where username = ? and password = ?";
// 获取SQL对象
pstmt = conn.prepareStatement(sql);
// 给?赋值
pstmt.setString(1,username);
pstmt.setString(2,password);
// 执行SQL
rs = pstmt.executeQuery();
return rs.next();
} catch (SQLException e) {
e.printStackTrace();
}finally {
//释放资源
JDBCUtils.close(pstmt, conn, rs);
}
return false;
}
}
MySQL database table (user):
Results of the:
1. Successful login:
2. The result of preventing SQL injection: