码迷,mamicode.com
首页 > 数据库 > 详细

PreparedStatement可以有效地防止sql被注入

时间:2016-09-13 14:57:35      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

 

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被注入

标签:

原文地址:http://www.cnblogs.com/linst/p/5868449.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!