zoukankan      html  css  js  c++  java
  • JDBC——PreparedStatement

    为什么要使用PreparedStatement

       1.使用Statement需要拼写SQL语句,很辛苦且很容易出错

       2.可以有效地禁止SQL注入

     SQL 注入是利用某些系统没有对用户输入的数据进行充分的检查,而在用户输入数据中注入非法的 SQL 语句段或命令,从而利用系统的 SQL 引擎完成恶意行为的做法

      对于 Java 而言,要防范 SQL 注入,只要用 PreparedStatement 取代 Statement 就可以了

      SELECT * FROM users WHERE username = 'a' OR password = 'AND password = ' OR '1' = '1';

      String username = "a' OR password = ";

      String password = " OR '1' = '1";

    String sql = "SELECT * FROM users WHERE username='"+ username +"' AND password='"+ password +"'";

    使用PreparedStatement代替Statement的话

    String sql = "SELECT * FROM users WHERE username = ? AND password = ?";

    PreparedStatement:是Statement的子接口,可以传入带占位符的SQL语句,并且提供了补充占位符变量的方法

    package jdbc;
    import java.util.Date;
    import org.junit.Test;
    
    import com.mysql.jdbc.Connection;
    import com.mysql.jdbc.PreparedStatement;
    
    /**
     使用PreparedStatement 是Statement的子接口,可以传入带占位符的SQL语句,并且提供了补充占位符变量的地方
    1.创建PreparedStatement
     	String sql = "INSERT INTO examstudent VALUES(?,?,?,?,?,?,?)"
     	PreparedStatement ps = conn.prepareStatement(sql);
    
    2.调用PreparedStatement的SetXxx(int index, Object val)设置占位符的值 (index的值从1开始)
     
    3.执行SQL语句:executeQuery()或executeUpdate(),注意:执行时不再需要传入sql语句
    
     */
    public class TestPreparedStatement {
    	@Test
    	public void TestPreparedStatement() {
    		Connection conn = null;
    		PreparedStatement preparedStatement = null;
    		
    		try {
    			conn = (Connection) JDBCTools.getConnection();
    			String sql = "INSERT INTO customer VALUES(?,?,?,?)";
    			preparedStatement = (PreparedStatement) conn.prepareStatement(sql);
    			
    			preparedStatement.setInt(1, 1);
    			preparedStatement.setString(2, "Skye");
    			preparedStatement.setString(2, "skye@163.com");
    			preparedStatement.setDate(3, (java.sql.Date) new Date(new java.util.Date().getTime()));
    			
    			preparedStatement.executeUpdate();
    		}catch(Exception e) {
    			e.printStackTrace();
    		}finally {
    			JDBCTools.release(null, preparedStatement, conn);
    		}
    	}
    }
    

     

  • 相关阅读:
    地址打开eclipse汉化全程
    可行性nullpoj 2723 Get Luffy Out 2sat
    服务器端提交Git版本控制tag标签的使用(二)
    原因总结六级之阅读理解
    子类父类浅谈filter里面为什么要强制转换成httpServletRequest类型
    排序中文POJ 1696/hrbustoj 1318 几何 蛋疼的蚂蚁
    选择复选框js限制checkbox勾选的个数以及php获取多个checkbbox的方法
    环境节点[置顶] 如何终止特定 RAC 实例上的 session
    整数实例hdu2041(超级楼梯)
    属性框架Fixjs——显示基类DisplayObject
  • 原文地址:https://www.cnblogs.com/SkyeAngel/p/7844417.html
Copyright © 2011-2022 走看看