Mybatis中 # 和 $ 占位符的区别

一、# 占位符

语法:#{字符}

mybatis处理#{}使用jdbc对象是PreparedStatement对象

<select id="selectStudentById" parameterType="integer" 		   	     resultType="com.itjuzi.entity.Student">
        select id,name,email,age from Student where id = #{
     id}
</select>

即mybatis创建PreparedStatement对象,执行sql语句

String sql = "select id,name,email,age from Student where id = ?";
PreparedStatement pst = conn.preparedStatement(sql);
pst.setInt(1,1001); //传递参数
ResultSet rs = pst.executeQuery(); //执行sql语句

#{} 特点

1)使用PreparedStatement对象,执行sql语句,效率高;

2)使用PreparedStatement对象,能避免sql注入,sql语句执行更安全;

3)#{} 常常作为列值使用,位于等号右侧,#{}位置的值和数据类型有关的,即 ? 是使用什么setXXX();

二、$ 占位符

语法:${字符}

mybatis执行${}占位符的sql语句

<select id="selectStudentById" parameterType="Integer" 		   	     resultType="com.itjuzi.entity.Student">
        select id,name,email,age from Student where id = ${
     id}
</select>

表 示 字 符 串 连 接 , 把 s q l 语 句 的 其 它 内 容 和 {}表示字符串连接,把sql语句的其它内容和 sql{}内容使用,字符串(+)连接的方式连在一起

mybatis创建Statement对象,执行sql语句

String sql = "select id,name,email,age from Student where id = " + "1001" ;
Statement stmt = conn.createStatement(sql);
ResultSet rs = stmt.executeQuery();

${} 特点

1)使用Statement对象,执行sql语句,效率低;

2)${}占位符的值,使用的是字符串连接的方式,有sql注入的风险;

3)${}数据是原样使用,不会区分数据类型,注意如字符串类型数据需要加引号 ’ 数据 ';

4)${}常用作表名或列名,在能抱住数据安全的情况下使用;

你可能感兴趣的:(Mybatis学习,java,mybatis,sql)