PreparedStatement防sql注入

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);
		}
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值