首页 > 代码库 > PreparedStatement可以有效地防止sql被注入
PreparedStatement可以有效地防止sql被注入
import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.Statement;import org.junit.Test;import util.JdbcUtil;/** * 模拟用户登录效果 * @author APPle * */public class Demo2 { //模拟用户输入 //private String name = "ericdfdfdfddfd‘ OR 1=1 -- "; private String name = "eric"; //private String password = "123456dfdfddfdf"; private String password = "123456"; /** * Statment存在sql被注入的风险 */ @Test public void testByStatement(){ Connection conn = null; Statement stmt = null; ResultSet rs = null; try { //获取连接 conn = JdbcUtil.getConnection(); //创建Statment stmt = conn.createStatement(); //准备sql String sql = "SELECT * FROM users WHERE NAME=‘"+name+"‘ AND PASSWORD=‘"+password+"‘"; //执行sql rs = stmt.executeQuery(sql); if(rs.next()){ //登录成功 System.out.println("登录成功"); }else{ System.out.println("登录失败"); } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { JdbcUtil.close(conn, stmt ,rs); } } /** * PreparedStatement可以有效地防止sql被注入 */ @Test public void testByPreparedStatement(){ Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { //获取连接 conn = JdbcUtil.getConnection(); String sql = "SELECT * FROM users WHERE NAME=? AND PASSWORD=?"; //预编译 stmt = conn.prepareStatement(sql); //设置参数 stmt.setString(1, name); stmt.setString(2, password); //执行sql rs = stmt.executeQuery(); if(rs.next()){ //登录成功 System.out.println("登录成功"); }else{ System.out.println("登录失败"); } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { JdbcUtil.close(conn, stmt ,rs); } }}
PreparedStatement可以有效地防止sql被注入
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。