#和$的区别

MyBatis启用了预编译功能

#{}:在预编译过程中,会把#{}部分用一个占位符?代替,执行时,将入参替换编译好的sql中的占位符“?”,能够很大程度防止sql注入

${}:在预编译过程中,${}会直接参与sql编译,直接显示数据,无法防止Sql注入,一般用于传入表名或order by动态参数

MyBatis是如何做到SQL预编译的呢?

其实在框架底层,是JDBC中的PreparedStatement类在起作用

Statement代码

public void insertStatement(){
    Connection conn=null;
    Statement statement=null;        
    try {
        conn=JDBCTools.getConnection2();
        statement=conn.createStatement();
        statement.executeUpdate("insert into t_student(name,age,email) values('zs',18,'[email protected]')");//执行sql语句
    } catch (Exception e) {
        e.printStackTrace();
    }finally{
        statement.close();
        conn.close();
    }        
}

PreparedStatement代码

public void insertPreparedStatement(){
    Connection conn=null;
    PreparedStatement preStatement=null;//创建PreparedStatement对象
    try {
        conn=JDBCTools.getConnection2();
        String sql="insert into t_student(name,age,email) values(?,?,?)";
        preStatement=conn.prepareStatement(sql);
        preStatement.setString(1, "klkl");
        preStatement.setInt(2, 12);
        preStatement.setString(3, "kkk@jjj");
        preStatement.executeUpdate();//执行sql
    } catch (Exception e) {
        e.printStackTrace();
    }finally{
        statement.close();
        conn.close();
    }
}

猜你喜欢

转载自www.cnblogs.com/yifanSJ/p/9095926.html