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

     

  • 相关阅读:
    Python3 使用requests请求,解码时出错:'utf8' codec can't decode byte 0x83 in position 1: invalid start byte
    快速上手阿里云oss SDK
    peewee 通俗易懂版
    gunicorn开启、关闭和重启
    Vector和ArrayList区别
    Hibernate与MyBatis
    redis缓存
    Innodb学习
    基本数据结构-图
    基本数据结构-树
  • 原文地址:https://www.cnblogs.com/SkyeAngel/p/7844417.html
Copyright © 2011-2022 走看看