import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
import JDBC.SqlHelper;
public class UserLoginDemo {
// 要防止 sql 注入,拼接字符串作为 sql 语句容易被 sql 注入
// Statement 容易被注入
// 防止被注入的方法:进行字符串过滤
// 试用执行计划的方法来进行 sql 语句的执行, 使用 PreparedStatement
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("请输入账号:");
Scanner in = new Scanner(System.in);
int id = Integer.parseInt(in.nextLine());
System.out.println("请输入密码:");
String pass = in.nextLine();
boolean bol = JudgeUserMessageByPreparedStatement(id, pass);
boolean bol1 = JudgeUserMessageByStatement(id, pass);
if(bol && bol1) {
System.out.println("认证成功");
}else {
System.out.println("账号或密码错误");
}
in.close();
}
public static boolean JudgeUserMessageByPreparedStatement(int id, String pass) {
Connection conn = null;
try {
conn = SqlHelper.getConnection();
String sql = "SELECT id, name FROM jdbc_table_2 "
+ "WHERE id = ? AND name = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, id);
ps.setString(2, pass);
ResultSet rs = ps.executeQuery();
if(rs.next()) {
return true;
}else {
return false;
}
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}finally {
SqlHelper.close(conn);
}
}
// 容易被 sql 注入攻击
public static boolean JudgeUserMessageByStatement(int id, String pass) {
Connection conn = null;
try {
conn = SqlHelper.getConnection();
String sql = "SELECT id, name FROM jdbc_table_2 "
+ "WHERE id = \'"+id+"\' AND name = \'"+pass+"\'";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
if(rs.next()) {
return true;
}else {
return false;
}
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}finally {
SqlHelper.close(conn);
}
}
}